def test_plan( self, mock_action: MagicMock, cfngin_fixtures: Path, tmp_path: Path, patch_safehaven: MagicMock, ) -> None: """Test plan.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) context = self.get_context() cfngin = CFNgin(ctx=context, sys_path=tmp_path) cfngin.plan() mock_action.assert_called_once() mock_instance.execute.assert_called_once_with() patch_safehaven.assert_has_calls( [ call(environ=context.env.vars), call.__enter__(), call(), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ] )
def test_deploy(self, mock_action, cfngin_fixtures, tmp_path, patch_safehaven): """Test deploy with two files & class init.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) copy_fixture( src=cfngin_fixtures / "configs" / "basic.yml", dest=tmp_path / "basic2.yml" ) context = self.get_context() context.env_vars["CI"] = "1" cfngin = CFNgin( ctx=context, parameters={"test_param": "test-param-value"}, sys_path=str(tmp_path), ) # support python < 3.6 cfngin.deploy() assert cfngin.concurrency == 0 assert not cfngin.interactive assert cfngin.parameters.bucket_name == "cfngin-bucket" assert cfngin.parameters.environment == "test" assert cfngin.parameters.namespace == "test-namespace" assert cfngin.parameters.region == "us-east-1" assert cfngin.parameters.test_key == "test_value" assert cfngin.parameters.test_param == "test-param-value" assert cfngin.recreate_failed assert cfngin.region == "us-east-1" assert cfngin.sys_path == str(tmp_path) assert not cfngin.tail assert mock_action.call_count == 2 mock_instance.execute.has_calls( [{"concurrency": 0, "tail": False}, {"concurrency": 0, "tail": False}] ) patch_safehaven.assert_has_calls( [ call( environ=context.env_vars, sys_modules_exclude=["awacs", "troposphere"], ), call.__enter__(), call( argv=["stacker", "build", str(tmp_path / "basic.yml")], sys_modules_exclude=["awacs", "troposphere"], ), call.__enter__(), call.__exit__(None, None, None), call( argv=["stacker", "build", str(tmp_path / "basic2.yml")], sys_modules_exclude=["awacs", "troposphere"], ), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ] )
def test_deploy(self, mock_action, cfngin_fixtures, tmp_path, patch_safehaven): """Test deploy with two files & class init.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) copy_fixture(src=cfngin_fixtures / 'configs' / 'basic.yml', dest=tmp_path / 'basic2.yml') context = self.get_context() context.env_vars['CI'] = '1' cfngin = CFNgin(ctx=context, parameters={'test_param': 'test-param-value'}, sys_path=str(tmp_path)) # support python < 3.6 cfngin.deploy() assert cfngin.concurrency == 0 assert not cfngin.interactive assert cfngin.parameters.bucket_name == 'cfngin-bucket' assert cfngin.parameters.environment == 'test' assert cfngin.parameters.namespace == 'test-namespace' assert cfngin.parameters.region == 'us-east-1' assert cfngin.parameters.test_key == 'test_value' assert cfngin.parameters.test_param == 'test-param-value' assert cfngin.recreate_failed assert cfngin.region == 'us-east-1' assert cfngin.sys_path == str(tmp_path) assert not cfngin.tail assert mock_action.call_count == 2 mock_instance.execute.has_calls([{ 'concurrency': 0, 'tail': False }, { 'concurrency': 0, 'tail': False }]) patch_safehaven.assert_has_calls([ call(environ=context.env_vars, sys_modules_exclude=['awacs', 'troposphere']), call.__enter__(), call(argv=['stacker', 'build', str(tmp_path / 'basic.yml')], sys_modules_exclude=['awacs', 'troposphere']), call.__enter__(), call.__exit__(None, None, None), call(argv=['stacker', 'build', str(tmp_path / 'basic2.yml')], sys_modules_exclude=['awacs', 'troposphere']), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ])
def _prepare_for_make_response(self, settings, expected_exc_class=None): # request mock self.request = MagicMock() self.request.matchdict = {'request_id': sen.request_id} self.manage_api = self.request.registry.manage_api self.manage_api.__enter__.return_value = self.manage_api self.manage_api.get_request_case.side_effect = self._side_effect__get_request_case # view instance self.configurator = MagicMock() self.configurator.registry.settings = settings concrete_cls = DeviceRequestGetViewBase.concrete_view_class( resource_id=sen.resource_id, config=self.configurator) self.view = concrete_cls(sen.context, self.request) # defaults for stuff used in _side_effect__get_request_case() self.cert_dn = None self.status = sen.NOT_SET self.status_changed_on = sen.NOT_SET # expected ManageAPI method calls self.expected_manage_api_calls = [ call.__enter__(), call.get_request_case(sen.request_id), call.__exit__(expected_exc_class, ANY, ANY), ]
def test_save(self, requests_mock, open_mock, soup_mock): """ Tests saving of content when request is successfull. """ # Given url = "http://example.com" expected_result = "<html></html>" requests_mock.return_value = MagicMock( status_code=200, content=expected_result, ) open_mock.return_value = open_mock soup_mock.return_value = soup_mock soup_mock.prettify.return_value = expected_result # When result = get_content(url, save_file=True) # Then self.assertEqual(result, expected_result) requests_mock.assert_called_once_with(url) open_mock.assert_has_calls([ call(url, "w"), call.__enter__(), call.__enter__().write(expected_result), call.__exit__(None, None, None), ]) soup_mock.assert_has_calls([ call(expected_result, "html.parser"), call.prettify(), ])
def test_read_from_file(self, requests_mock, isfile_mock, open_mock): """ Tests content when file exists (instead of calling url). """ # Given path = "/path/to/file.html" file_mock = MagicMock() expected_result = "<html></html>" isfile_mock.return_value = True open_mock.return_value = open_mock open_mock.__enter__.return_value = file_mock file_mock.read.return_value = expected_result # When result = get_content(path) # Then self.assertEqual(result, expected_result) self.assertFalse(requests_mock.called) open_mock.assert_has_calls([ call(path, "r"), call.__enter__(), call.__enter__().read(), call.__exit__(None, None, None), ]) file_mock.read.assert_called_once_with()
def _assert_db_operations_as_expected(self, expected_db_obj=None, expected_exc_type=None): self.assertEqual(self.auth_db_connector_mock.mock_calls, [ call.__enter__(), call.get_current_session(), call.get_current_session().add(ANY), call.__exit__(expected_exc_type, ANY, ANY), ]) if expected_db_obj is None: self.assertEqual(self.added_to_session, []) else: self.assertEqual(len(self.added_to_session), 1) self.assertEqual(self.added_to_session[0], expected_db_obj)
def test_plan(self, mock_action, cfngin_fixtures, tmp_path, patch_safehaven): """Test plan.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) context = self.get_context() cfngin = CFNgin(ctx=context, sys_path=str(tmp_path)) cfngin.plan() mock_action.assert_called_once() mock_instance.execute.assert_called_once_with() patch_safehaven.assert_has_calls( [ call(environ=context.env_vars), call.__enter__(), call(argv=["stacker", "diff", str(tmp_path / "basic.yml")]), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ] )
def test_success(self, open_mock): """ Tests json file is saved when valid format is provided. """ # Given data = { "name": { "name": "name", "costs": { "gold": 3, "energy": 4, "green": 5, "blue": 6, "red": 7, }, "stats": { "attack": 15, "health": 10, }, "attributes": { "supply": 8, "frontline": True, "fragile": False, "blocker": True, "prompt": False, "stamina": 16, "lifespan": 19, "build_time": 9, "exhaust_turn": 17, "exhaust_ability": 18, }, "links": { "path": "/name", }, "type": 1, "unit_spell": "unit/spell", } } json_data = json.dumps( data, sort_keys=True, indent=4, separators=(",", ": ")) expected_result = {"message": "Success"} open_mock.return_value = open_mock # When result = export_units_json(data, file_name=self.file_name) # Then self.assertEqual(result, expected_result) open_mock.assert_has_calls([ call(self.file_name, "w"), call.__enter__(), call.__enter__().write(json_data), call.__exit__(None, None, None), ])
def test_destroy(self, mock_action, cfngin_fixtures, tmp_path, patch_safehaven): """Test destroy.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) context = self.get_context() cfngin = CFNgin(ctx=context, sys_path=str(tmp_path)) cfngin.destroy() mock_action.assert_called_once() mock_instance.execute.assert_called_once_with(concurrency=0, force=True, tail=False) patch_safehaven.assert_has_calls([ call(environ=context.env_vars), call.__enter__(), call(argv=['stacker', 'destroy', str(tmp_path / 'basic.yml')]), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ])
def test_run_no_relays_on(self): self._subject.run(test_mode=True) assert_that( self._subject._arduino_timeout_relays.mock_calls, equal_to([ call.__enter__(), call.relay_off(1), call.relay_off(2), call.relay_off(1), call.relay_off(2), call.__exit__(None, None, None) ]) )
def _prepare_for_make_response_calling_get_cert( self, settings=None, expected_exc_class=None): self._prepare_for_make_response(settings) self.manage_api.get_cert.side_effect = self._side_effect__get_cert # to be returned by _side_effect__get_cert() self.cert_data = MagicMock() # defaults for stuff used in _side_effect__get_cert() self.cert_pem = self.SOME_CERT_PEM self.cert_expires_on = self.DT_TOMMOROW self.cert_revoked_on = None # expected ManageAPI method calls (overwritten) self.expected_manage_api_calls = [ call.__enter__(), call.get_request_case(sen.request_id), call.get_cert(self.SOME_CERT_CA_LABEL, self.SOME_CERT_SERIAL_NUMBER), call.__exit__(expected_exc_class, ANY, ANY), ]
def test_read(self): """ there's some crazyness here trying to mock open() with different return values depending on the path """ sensors = [ { 'address': 'sensor1', 'temp_path': '/foo/bar/one' }, { 'type': 'mytype', 'alias': 'myalias', 'address': 'sensor2', 'temp_path': '/foo/bar/two' }, { 'address': 'sensor3', 'temp_path': '/foo/bar/three' } ] exc = Exception() def se_exc(*args): raise exc mock_one = MagicMock(name='mock_one') mock_one.__enter__.return_value.read.return_value = '11.234' m_one = mock_open(mock=mock_one) mock_two = MagicMock(name='mock_two') mock_two.__enter__.return_value.read.return_value = '22.567' m_two = mock_open(mock=mock_two) mock_three = MagicMock(name='mock_three') mock_three.__enter__.return_value.read.side_effect = se_exc m_three = mock_open(mock=mock_three) mock_other = MagicMock(name='mock_other') mock_other.__enter__.return_value.read.return_value = '999.99' m_other = mock_open(mock=mock_other) def se_opn(*args): print(args) if args[0] == '/foo/bar/one': return m_one if args[0] == '/foo/bar/two': return m_two if args[0] == '/foo/bar/three': return m_three return m_other with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch('%s._find_sensors' % pb, autospec=True) as mock_find: with patch('%s.open' % pbm, create=True) as mock_opn: mock_opn.side_effect = se_opn mock_find.return_value = sensors res = self.cls.read() assert mock_find.mock_calls == [call(self.cls)] assert mock_opn.mock_calls == [ call('/foo/bar/one', 'r'), call('/foo/bar/two', 'r'), call('/foo/bar/three', 'r') ] assert m_one.mock_calls == [ call.__enter__(), call.__enter__().read(), call.__exit__(None, None, None) ] assert m_two.mock_calls == [ call.__enter__(), call.__enter__().read(), call.__exit__(None, None, None) ] # third arg to third call is a traceback, so assert about everything # else assert len(m_three.mock_calls) == 3 assert m_three.mock_calls[0] == call.__enter__() assert m_three.mock_calls[1] == call.__enter__().read() # third call is __exit__ assert m_three.mock_calls[2][0] == '__exit__' # first and second args to that third call... assert m_three.mock_calls[2][1][0] == type(exc) assert m_three.mock_calls[2][1][1] == exc assert m_other.mock_calls == [] assert mock_logger.mock_calls == [ call.debug('Reading temperature from sensor %s at %s', 'sensor1', '/foo/bar/one'), call.debug('Got temperature of %s from %s', 11.234, 'sensor1'), call.debug('Reading temperature from sensor %s at %s', 'sensor2', '/foo/bar/two'), call.debug('Got temperature of %s from %s', 22.567, 'sensor2'), call.debug('Reading temperature from sensor %s at %s', 'sensor3', '/foo/bar/three'), call.debug('Exception reading from sensor %s', 'sensor3', exc_info=1) ] assert res == { 'sensor1': { 'type': None, 'value': 11.234 }, 'sensor2': { 'type': 'mytype', 'alias': 'myalias', 'value': 22.567 }, 'sensor3': { 'type': None, 'value': None } }