def test_error_on_set_up_some_other_errors(self): test_case = {'my': 'case'} test_fixture = [{'foo': 'bar'}] test_fixture_results = [{ 'baz': None }] # type: List[Dict[six.text_type, Optional[ActionResponse]]] test = MockedTestCase() case_data = mock.MagicMock() case_data.fixture_name = 'bbb' case_data.test_fixture = test_fixture test_function = test._create_test_function('aaa', 'bbb', test_case, test_fixture, test_fixture_results) test_function._last_fixture_test = True # type: ignore test._pytest_first_fixture_case = case_data # type: ignore test._pytest_last_fixture_case = case_data # type: ignore test.tear_down_test_fixture.side_effect = Error3() with mock.patch('pysoa.test.server.PyTestServerTestCase.setup_method') as mock_setup_method, \ mock.patch('pysoa.test.server.PyTestServerTestCase.teardown_method') as mock_teardown_method: mock_setup_method.side_effect = Error1() mock_teardown_method.side_effect = Error2() with pytest.raises(Error1): test.setup_method() with pytest.raises(Error2): test.teardown_method() test.set_up_test_fixture.assert_called_once_with(test_fixture) test.tear_down_test_fixture.assert_called_once_with(test_fixture) test.set_up_test_case.assert_not_called() test.tear_down_test_case.assert_not_called() test.set_up_test_case_action.assert_not_called() test.tear_down_test_case_action.assert_not_called() test._run_test_case.assert_not_called() mock_dir = cast(mock.MagicMock, test._all_directives[0]) mock_dir.return_value.set_up_test_fixture.assert_called_once_with( test_fixture) mock_dir.return_value.assert_test_fixture_results.assert_not_called() mock_dir.return_value.tear_down_test_fixture.assert_called_once_with( test_fixture) mock_dir.return_value.set_up_test_case.assert_not_called() mock_dir.return_value.tear_down_test_case.assert_not_called() mock_dir.return_value.set_up_test_case_action.assert_not_called() mock_dir.return_value.tear_down_test_case_action.assert_not_called() assert test.add_error.call_count == 1 assert test.setUpClass.call_count == 0 assert test.tearDownClass.call_count == 0
async def test_default_coroutine_middleware(): class SpecialError(Exception): pass context = {'i': 0} # noinspection PyCompatibility async def coroutine(): context['i'] += 1 if context['i'] > 2: return 'bar_returned_by_coroutine' raise SpecialError(context['i']) thread = AsyncEventLoopThread([DefaultCoroutineMiddleware()]) thread.start() with mock.patch('logging.Logger.exception') as mock_log_exception: future = thread.run_coroutine(coroutine()) await asyncio.sleep(0.01) with pytest.raises(SpecialError) as error_context: future.result() assert error_context.value.args[0] == 1 mock_log_exception.assert_called_once_with( 'Error occurred while awaiting coroutine in request.run_coroutine') mock_log_exception.reset_mock() future = thread.run_coroutine(coroutine()) await asyncio.sleep(0.01) with pytest.raises(SpecialError) as error_context: future.result() assert error_context.value.args[0] == 2 mock_log_exception.assert_called_once_with( 'Error occurred while awaiting coroutine in request.run_coroutine') mock_log_exception.reset_mock() future = thread.run_coroutine(coroutine()) await asyncio.sleep(0.01) assert future.result() == 'bar_returned_by_coroutine' assert mock_log_exception.call_count == 0 thread.join()
def _start_patches(test_target): if 'mock_patches' in test_target: for mock_target, config in six.iteritems(test_target['mock_patches']): config['patcher'] = unittest_mock.patch(mock_target, new=unittest_mock.MagicMock()) config['magic_mock'] = config['patcher'].start() if config['configure']: # The code in this came, and is slightly modified, from unittest.mock.Mock # "We sort on the number of dots so that attributes are set before we set attributes on attributes" for path, value in sorted(config['configure'].items(), key=lambda e: e[0].count('.')): paths = path.split('.') final = paths.pop() obj = config['magic_mock'] for entry in paths: obj = getattr(obj, entry) if value is _DELETE_ATTRIBUTE: delattr(obj, final) else: setattr(obj, final, value)
async def test_default_coroutine_middleware(): class SpecialError(Exception): pass # noinspection PyCompatibility async def coroutine(): raise SpecialError() thread = AsyncEventLoopThread([DefaultCoroutineMiddleware()]) thread.start() with mock.patch('logging.Logger.exception') as mock_log_exception: thread.run_coroutine(coroutine()) await asyncio.sleep(0.2) thread.join() mock_log_exception.assert_called_once_with( 'Error occurred while awaiting coroutine in request.run_coroutine')
def setup_module(_): """ We want this setup to run before any of the tests in this module, to ensure that the `standalone` module gets imported. """ global standalone with mock.patch( 'pysoa.utils.get_python_interpreter_arguments') as mock_get_args: prev_path_0 = sys.path[0] mock_get_args.return_value = ['python', '/path/to/module.py'] # Force this to bad sys.path[0] = '/path/to/module.py' try: from pysoa.server import standalone # type: ignore assert False, 'Should not have been able to import standalone; should have received SystemExit' except SystemExit as e: # This first bit is actually a test; it confirms that the double-import trap is triggered assert e.args[0] == 99 finally: # ...and then we put this back so that we haven't caused any problems. sys.path[0] = prev_path_0 # Now we actually import the module, but we have to make sure the double-import trap isn't triggered before we # do. Running `pytest` or `setup.py` looks to `standalone` like there is a problem, so we temporarily remove # `pytest` or `setup.py` from the first path item if it's Py<3.7, change return value of mock for 3.7+... if sys.version_info < (3, 7): sys.path[0] = '' else: mock_get_args.return_value = ['python', '-m', 'service_module'] try: from pysoa.server import standalone # type: ignore except SystemExit as e: assert False, 'Expected import to succeed, instead got SystemExit with code {}'.format( e.args[0]) finally: # ...and then we put this back so that we haven't caused any problems. sys.path[0] = prev_path_0
def test_reset_tokens(with_context_var): if with_context_var: context = _fake_context_manager() # type: ignore else: context = mock.patch('pysoa.common.compatibility.contextvars', new=None) # type: ignore with context: var1 = ContextVar('test_reset_tokens1', default='foo') # type: ContextVar[six.text_type] var2 = ContextVar('test_reset_tokens2', default='bar') # type: ContextVar[six.text_type] var3 = ContextVar( 'test_reset_tokens3') # type: ContextVar[six.text_type] token1 = var1.set('hello') token2 = var2.set('goodbye') assert var1.get() == 'hello' assert var2.get() == 'goodbye' with pytest.raises(ValueError): var1.reset(token2) with pytest.raises(ValueError): var2.reset(token1) assert var1.get() == 'hello' assert var2.get() == 'goodbye' if not with_context_var: bad_token1 = _ContextVarToken(var1, None) # type: ignore bad_token2 = _ContextVarToken(var2, None) # type: ignore else: bad_token1 = _ThreadLocalToken(var1, None) # type: ignore bad_token2 = _ThreadLocalToken(var2, None) # type: ignore with pytest.raises(TypeError): var1.reset(bad_token1) with pytest.raises(TypeError): var2.reset(bad_token2) assert var1.get() == 'hello' assert var2.get() == 'goodbye' var1.reset(token1) assert var1.get() == 'foo' assert var2.get() == 'goodbye' var2.reset(token2) assert var1.get() == 'foo' assert var2.get() == 'bar' token1a = var1.set('hello') token2a = var2.set('goodbye') assert var1.get() == 'hello' assert var2.get() == 'goodbye' token1b = var1.set('world') token2b = var2.set('universe') assert var1.get() == 'world' assert var2.get() == 'universe' var2.reset(token2b) assert var1.get() == 'world' assert var2.get() == 'goodbye' var1.reset(token1b) assert var1.get() == 'hello' assert var2.get() == 'goodbye' var1.reset(token1a) var2.reset(token2a) assert var1.get() == 'foo' assert var2.get() == 'bar' token3 = var3.set('baz') assert var3.get() == 'baz' var3.reset(token3) assert var3.get(default='qux') == 'qux' with pytest.raises(LookupError): var3.get()