Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id)
def add_something(
self,
*,
argument1,
argument1 = None,
):
"""adding something"""
I've written tests for the given as below.
@patch("other inside function to mock")
@patch("other insdie function to mock 2")
def test_add_something(
self, mock_1, mock_2
):
""" some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
1 answer
-
answered 2022-05-07 06:14
MusicalNinja
It looks like at least one of your decorators don't handle taking and passing on the arguments properly. Can you post the code for
@patch()
and@retry_if_access_token_expired()
?They should have the generic form from here: https://realpython.com/primer-on-python-decorators/#decorators-with-arguments
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Upload file from html when block public access is true
I am using
django-s3direct
to file uploadhttps://github.com/bradleyg/django-s3direct
Using IAM role setting because I upload the file from the server on ECS container.
Now I set the
blockPublicAccess
ofS3
false.When uploading images from html, there comes error.
https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403
OK, it is understandable.
Browser try to access the for initiation.
However there is any way to upload file from browser when blockPublicAccess is true??
-
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data
Thanks in advance!
-
Kotlin Coroutines Unit Testing
Im trying to test this suspend function:
suspend fun <T> getResult(call: suspend () -> Response<T>): Resource<T> { val response = call() val body = response.body() val code = response.code() if (response.isSuccessful) { Log.d(Cybrid.instance.tag, "Data: ${response.code()} - ${response.body()}") return Resource.success(body!!, code) } else if (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) { Cybrid.instance.let { cybrid -> cybrid.listener.let { cybrid.invalidToken = true it?.onTokenExpired() } } Log.e(Cybrid.instance.tag, "Error - Something wrong with TOKEN : ${response.code()} ${response.message()}") return Resource.error(response.message(), code=response.code()) } else { Log.e(Cybrid.instance.tag, "Error - Other: ${response.code()} ${response.message()} :: ${response.raw()}") return Resource.error(message = response.message(), data= response.body(), code= response.code()) } }
With this Unit Test Case, all it cover except line 13 , I dont know how to cover the line!!!
@ExperimentalCoroutinesApi @Test fun get400ErrorServerTest() = runBlocking { Cybrid.instance.setBearer("Bearer") val pricesService = AppModule.getClient().createService(PricesApi::class.java) val result = getResult { pricesService.listPrices() } Assert.assertNotNull(result) Assert.assertEquals(result.code, 400) Assert.assertNull(result.data) }
The coverage report says:
Some idea to get coverage for line 13 ??? Thnanks
-
Unit testing with get request
I am trying to create a unit test for one of my api.
In the frontend, I send it this way...
params = { participants: JSON.stringify(participants), section: JSON.stringify(section), }; axios.get('/api/list', params)
while in the controller, it receives the params this way...
public function list(Request $request) { $participants = json_decode($request->participants); $section = json_decode($request->section); }
Now, I tried making a unit test out of this. by doing...
$params = [ 'participants' => ['id', 'name', 'rating'], 'section' => ['id', 'code'], ]; $this->get('/api/list'.http_build_query($params))->assertStatus(200) // $this->json('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->getJson('/api/list', $params)->assertStatus(200) // -> also tried this one // $this->call('GET', '/api/list', $params)->assertStatus(200) // -> also tried this one
But none of them works, it always says
TypeError: json_decode(): Argument #1 ($json) must be of type string, array given
.So, the way I built the url and the params must be all wrong,
so my question here is that, what's the correct way of building the url so that it provides a correct url string format and the controller will json_decode the params?
-
Pytest does not find my tests in Poetry project (VSCode finds)
I've just created my first Python package using Poetry using the usual
poetry new mypackage
command. My problem is thatpytest
does not execute any test when I run it. I'm developing using VSCode and the weird behavior is that VSCode successfully finds and executes my tests.Poetry created a subdir called
mypackage
and another calledtests
. My test file is calledtests/test_mypackage.py
.VSCode autodiscoverd the tests, and display them in the test tab. The
.vscode/settings.json
file has this configuration:"python.testing.pytestArgs": [ "tests" ],
I've tried the following commands to execute pytest:
- With my venv manually activated:
pytest
pytest tests
pytest tests/test_mypackage.py
cd tests;pytest test_mypackage.py
- without my venv activated:
poetry run pytest
poetry run pytest tests
The behavior is always the same: nothing happens, as if pytest couldn't detect anything to run.
I've been using VSCode to run the tests, but now I want to put the code under Continuous Integration. How do I run pytest to validate my package?
- With my venv manually activated:
-
Multiple flask calls in single pytest having different databases
So I'm trying to test an endpoint in flask that I need to call multiple times in one test. The issue I am having is that on the second request the objects I placed into the DB using pytest fixture with the scope of function do not appear in the db on that second call. Is this normal / is there a way to change this behavior? Using SqlAlchemy for ORM with a scoped_session. Thanks!