How to send requests with JSON in unit tests
Changing the post to response=self.app.post(‘/test_function’, data=json.dumps(dict(foo=’bar’)), content_type=”application/json”) fixed it. Thanks to user3012759.
Changing the post to response=self.app.post(‘/test_function’, data=json.dumps(dict(foo=’bar’)), content_type=”application/json”) fixed it. Thanks to user3012759.
Since Python 3.8 unittest comes with the IsolatedAsyncioTestCase function, designed for this purpose. from unittest import IsolatedAsyncioTestCase class Test(IsolatedAsyncioTestCase): async def test_functionality(self): result = await functionality() self.assertEqual(expected, result)
In general you add all prerequisite steps to setUp and all clean-up steps to tearDown. You can read more with examples here. When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each … Read more
When you @mock.patch(‘a.A’), you are replacing the class A in the code under test with mock_a. In B.method_b you then set a = A(), which is now a = mock_a() – i.e. a is the return_value of mock_a. As you haven’t specified this value, it’s a regular MagicMock; this isn’t configured either, so you get … Read more
The difference manifests itself when you have more than one test method in your class. setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method. For example: class Example(unittest.TestCase): @classmethod def setUpClass(cls): print(“setUpClass”) def setUp(self): print(“setUp”) def test1(self): print(“test1”) def test2(self): print(“test2”) def tearDown(self): … Read more
Individual test methods or classes can both be disabled using the unittest.skip decorator. @unittest.skip(“reason for skipping”) def test_foo(): print(‘This is foo test case.’) @unittest.skip # no reason needed def test_bar(): print(‘This is bar test case.’) For other options, see the docs for Skipping tests and expected failures.
When you are using the patch decorator from the unittest.mock package you are patching it in the namespace that is under test (in this case app.mocking.get_user_name), not the namespace the function is imported from (in this case app.my_module.get_user_name). To do what you describe with @patch try something like the below: from mock import patch from … Read more
This works as you suggest – you just have to specify the class name as well: python testMyCase.py MyCase.testItIsHot
With Python 2.7 and higher you don’t have to write new code or use third-party tools to do this; recursive test execution via the command line is built-in. Put an __init__.py in your test directory and: python -m unittest discover <test_directory> # or python -m unittest discover -s <directory> -p ‘*_test.py’ You can read more … Read more