def test_get_fortune_pass_many_attempts_at_str_magic_method(self): response = MagicMock() response.status_code = 200 response.content = _TEST_RAW_DATA session = MagicMock() session.get.return_value = response self._subject._session.__enter__.return_value = session # handful of calls [ assert_that(str(self._subject), equal_to(_TEST_DECODED_DATA)) for _ in range(0, 32) ] time.sleep(1) # a handful more calls for _ in range(0, 32): assert_that(str(self._subject), equal_to(_TEST_DECODED_DATA)) # but there are only two calls to the Session assert_that( session.mock_calls, equal_to([ call.get(self._subject._api_url), call.get(self._subject._api_url), ]))
def test_get_ip_address_nominal(self, mock_session_constructor): mock_response = Mock(spec=Response) mock_response.status_code = 200 mock_response.json.return_value = _TEST_IP_ADDRESS_DICT mock_session = Mock(spec=Session) mock_session.get.return_value = mock_response mock_session_constructor.return_value = mock_session self.assertEqual(self.subject.get_ip_address(), '66.42.111.104') # check calls against the constructor self.assertEqual( mock_session_constructor.mock_calls, [ call(), # construction call().get('http://ifconfig.co/json'), call().get().json() ]) # check calls against the object the constructor returns self.assertEqual( mock_session.mock_calls, [call.get('http://ifconfig.co/json'), call.get().json()])
def test_maven_config_opt_adapter(self): """Test class MavenConfigOptAdapter""" conf = mock.MagicMock() section = 'section' adapter = koji.util.MavenConfigOptAdapter(conf, section) self.assertIs(adapter._conf, conf) self.assertIs(adapter._section, section) conf.has_option.return_value = True adapter.goals adapter.properties adapter.someattr conf.has_option.return_value = False with self.assertRaises(AttributeError) as cm: adapter.noexistsattr self.assertEquals(cm.exception.args[0], 'noexistsattr') self.assertEquals(conf.mock_calls, [ call.has_option(section, 'goals'), call.get(section, 'goals'), call.get().split(), call.has_option(section, 'properties'), call.get(section, 'properties'), call.get().splitlines(), call.has_option(section, 'someattr'), call.get('section', 'someattr'), call.has_option(section, 'noexistsattr') ])
def test_run_test_one(self, capsys): conf = Mock() conf.get.return_value = { 'ep1': {'method': 'GET'} } args = Mock(endpoint_name='ep1') res1 = Mock(spec_set=Response) type(res1).status_code = 200 type(res1).content = 'res1content' type(res1).headers = { 'h1': 'h1val', 'hz': 'hzval' } req_data = { 'message': 'testing via webhook2lambda2sqs CLI', 'version': VERSION, 'host': 'mynode', 'datetime': '2016-07-01T02:03:04.000000' } with patch.multiple( pbm, autospec=True, requests=DEFAULT, logger=DEFAULT, get_base_url=DEFAULT, node=DEFAULT ) as mocks: mocks['get_base_url'].return_value = 'mybase/' mocks['node'].return_value = 'mynode' mocks['requests'].get.return_value = res1 run_test(conf, args) out, err = capsys.readouterr() assert err == '' expected_out = "=> Testing endpoint mybase/ep1/ with GET: " expected_out += pformat(req_data) + "\n" expected_out += "RESULT: HTTP 200\n" expected_out += "h1: h1val\n" expected_out += "hz: hzval\n" expected_out += "\nres1content\n\n" assert out == expected_out assert conf.mock_calls == [call.get('endpoints')] assert mocks['get_base_url'].mock_calls == [call(conf, args)] assert mocks['logger'].mock_calls == [ call.debug('API base url: %s', 'mybase/') ] assert mocks['requests'].mock_calls == [ call.get('mybase/ep1/', params={ 'message': 'testing via webhook2lambda2sqs CLI', 'version': VERSION, 'host': 'mynode', 'datetime': '2016-07-01T02:03:04.000000' }) ] assert mocks['node'].mock_calls == [call()]
def test_string_representation(self): self.config_parser.get.side_effect = lambda *x: { ('auth', 'username'): '<username>', ('auth', 'password'): '<password>'}[x] assert_that(str(self.config), is_(equal_to("Config(user: <username>, pass: **********)"))) assert_that(self.config_parser.mock_calls, contains( call.get('auth', 'username'), call.get('auth', 'password')))
def test_string_representation(self): self.config_parser.get.side_effect = lambda *x: { ('auth', 'username'): '<username>', ('auth', 'password'): '<password>'}[x] assert_that(str(self.config)).is_equal_to("Config(user: <username>, pass: **********)") assert_that(self.config_parser.mock_calls).contains( call.get('auth', 'username'), call.get('auth', 'password'))
def test_get_metric_with_overridden_granularities(self): slug = 'test-metric' self.r.get_metric(slug) # Verify that we GET the keys from redis day, week = self.r._build_keys(slug) self.redis.assert_has_calls([ call.get(day), call.get(week), ])
def test_mon_hosts(self): hosts = Mock() for (name, host) in mon_hosts(('name1', 'name2.localdomain', 'name3:1.2.3.6', 'name4:localhost.localdomain')): hosts.get(name, host) expected = [call.get('name1', 'name1'), call.get('name2', 'name2.localdomain'), call.get('name3', '1.2.3.6'), call.get('name4', 'localhost.localdomain')] result = hosts.mock_calls assert result == expected
def test_get_metric(self): """Tests getting a single metric; ``R.get_metric``.""" slug = 'test-metric' self.r.get_metric(slug) # Verify that we GET the keys from redis day, week, month, year = self.r._build_keys(slug) self.redis.assert_has_calls([ call.get(day), call.get(week), call.get(month), call.get(year), ])
def test_request_params(self, mock_requests): eh.servers_info() self.assertEqual( call.get('https://api-lon-b.elastichosts.com/drives/info', auth=(eh.USER, eh.SECRET_KEY), headers={'Accept': 'application/json'}), mock_requests.mock_calls[0]) self.assertEqual( call.get('https://api-lon-b.elastichosts.com/servers/info', auth=(eh.USER, eh.SECRET_KEY), headers={'Accept': 'application/json'}), mock_requests.mock_calls[1])
def test_get_metric_with_overridden_granularities(self): test_settings = TEST_SETTINGS.copy() test_settings['MIN_GRANULARITY'] = 'daily' test_settings['MAX_GRANULARITY'] = 'weekly' with override_settings(REDIS_METRICS=test_settings): slug = 'test-metric' self.r.get_metric(slug) # Verify that we GET the keys from redis day, week = self.r._build_keys(slug) self.redis.assert_has_calls([ call.get(day), call.get(week), ])
def test_get_db_connection_string(self): self.config_parser.get.side_effect = lambda *x: { ('db', 'host'): '<host>', ('db', 'dbname'): '<dbname>', ('db', 'username'): '<username>', ('db', 'password'): '<password>'}[x] assert_that(self.config.get_db_connection_string(), is_(equal_to("host='<host>' dbname='<dbname>' user='******' password='******'"))) assert_that(self.config_parser.mock_calls, contains( call.get('db', 'host'), call.get('db', 'dbname'), call.get('db', 'username'), call.get('db', 'password')))
def test_get_db_connection_string(self): self.config_parser.get.side_effect = lambda *x: { ('db', 'host'): '<host>', ('db', 'dbname'): '<dbname>', ('db', 'username'): '<username>', ('db', 'password'): '<password>'}[x] assert_that(self.config.get_db_connection_string()) \ .is_equal_to("host='<host>' dbname='<dbname>' user='******' password='******'") assert_that(self.config_parser.mock_calls).contains( call.get('db', 'host'), call.get('db', 'dbname'), call.get('db', 'username'), call.get('db', 'password'))
def test_ice_get_response_error(self, mock_requests, mock_logger): url = 'http://foo.com/dashboard/foobar' mock_result = Mock(status_code=200) mock_result.json.return_value = {"status": 503, "data": ["foo","bar"] } mock_requests.get.return_value = mock_result g = Groups('http://foo.com/', dry_run=False) mock_logger.reset_mock() self.assertRaises(APIRequestException, g._ice_get, 'foobar') self.assertEquals(mock_logger.mock_calls, [call.debug('GETing http://foo.com/dashboard/foobar')]) self.assertEquals(mock_requests.mock_calls, [ call.get('http://foo.com/dashboard/foobar', auth=None), call.get().json() ])
def test_get_ip_address_erroneous(self, mock_session_constructor): mock_session = Mock(spec=Session) mock_session.get.side_effect = ReadTimeout('connection timed out') mock_session_constructor.return_value = mock_session self.assertRaises( ReadTimeout, self.subject.get_ip_address, # method to call ) # check calls against the constructor self.assertEqual( mock_session_constructor.mock_calls, [ call(), # construction call().get('http://ifconfig.co/json'), # note: no .json() call ]) # check calls against the object the constructor returns self.assertEqual( mock_session.mock_calls, # check the calls against this object [ call.get('http://ifconfig.co/json'), # note: no .json() call ])
def test_get_ip_address_boundary(self, mock_session_constructor): mock_response = Mock(spec=Response) mock_response.status_code = 403 mock_session = Mock(spec=Session) mock_session_constructor.return_value = mock_session self.assertRaises( GetIPAddressError, self.subject.get_ip_address, # method to call ) # check calls against the constructor self.assertEqual( mock_session_constructor.mock_calls, [ call(), # construction call().get('http://ifconfig.co/json'), # note: no .json() call ]) # check calls against the object the constructor returns self.assertEqual( mock_session.mock_calls, # check the calls against this object [ call.get('http://ifconfig.co/json'), # note: no .json() call ])
def test_sonar_publish_sast(self, mock_get, mock_isfile): mock_get.side_effect = ['project_key', 'sources'] # Create FakeCommand verif_cmd = [ {'cmd': 'sonar-scanner -Dsonar.login=%s -Dsonar.host.url=%s -Dsonar.gitlab.user_token=%s -Dsonar.gitlab.commit_sha=%s -Dsonar.gitlab.ref_name=%s -Dsonar.gitlab.project_id=%s -Dsonar.branch.name=%s -Dsonar.gitlab.json_mode=SAST' % (TestCliDriver.cdp_sonar_login, TestCliDriver.cdp_sonar_url, TestCliDriver.gitlab_user_token, TestCliDriver.ci_commit_sha, TestCliDriver.ci_commit_ref_name, TestCliDriver.ci_project_path, TestCliDriver.ci_commit_ref_name), 'output': 'unnecessary'} ] self.__run_CLIDriver({ 'sonar', '--publish', '--sast' }, verif_cmd) mock_isfile.assert_called_with('sonar-project.properties') mock_get.assert_has_calls([call.get('sonar.projectKey'), call.get('sonar.sources')])
def test__init__using_defaults__no_ssl(self): connection_params_dict_mock = RLockedMagicMock() connection_params_dict_mock.get.return_value = False self.meth.__init__(connection_params_dict=connection_params_dict_mock, exchange='my-exchange') # attrs self.assertIs(self.mock._connection_params_dict, connection_params_dict_mock) self.assertEqual(self.mock._exchange, {'exchange': 'my-exchange'}) self.assertEqual(self.mock._exchange_name, 'my-exchange') self.assertEqual(self.mock._queues_to_declare, []) self.assertIsNone(self.mock._serialize) self.assertEqual(self.mock._prop_kwargs, AMQPThreadedPusher.DEFAULT_PROP_KWARGS) self.assertEqual(self.mock._mandatory, False) self.assertIs(self.mock._output_fifo.__class__, Queue.Queue) self.assertEqual(self.mock._output_fifo.maxsize, 20000) self.assertIsNone(self.mock._error_callback) # calls self.assertEqual(self.mock.mock_calls, [ call._setup_communication(), call._start_publishing(), ]) self.assertEqual(connection_params_dict_mock.mock_calls, [ call.get('ssl'), ])
def test_get_instance(mock_requests): _get_instance('id') assert mock_requests.mock_calls == [ call.get( 'http://metadata.google.internal/computeMetadata/v1/instance/id', headers={'Metadata-Flavor': 'Google'}) ]
def test_ice_get_no_data(self, mock_requests, mock_logger): url = 'http://foo.com/dashboard/foobar' mock_result = Mock(status_code=200) mock_result.json.return_value = {"status": 200} mock_requests.get.return_value = mock_result g = Groups('http://foo.com/', dry_run=False) mock_logger.reset_mock() res = g._ice_get('foobar') self.assertEquals(mock_logger.mock_calls, [call.debug('GETing http://foo.com/dashboard/foobar')] ) self.assertEquals(mock_requests.mock_calls, [ call.get('http://foo.com/dashboard/foobar', auth=None), call.get().json() ]) self.assertEquals(res, {})
def test_request_params(self, mock_requests): eh.servers_info() self.assertEqual( call.get( 'https://api-lon-b.elastichosts.com/drives/info', auth=(eh.USER, eh.SECRET_KEY), headers={'Accept': 'application/json'} ), mock_requests.mock_calls[0]) self.assertEqual( call.get( 'https://api-lon-b.elastichosts.com/servers/info', auth=(eh.USER, eh.SECRET_KEY), headers={'Accept': 'application/json'} ), mock_requests.mock_calls[1])
def test_ice_get_auth(self, mock_requests, mock_logger): url = 'http://foo.com/dashboard/foobar' mock_result = Mock(status_code=200) mock_result.json.return_value = {"status": 200, "data": ["foo","bar"] } mock_requests.get.return_value = mock_result g = Groups('http://foo.com/', dry_run=False) g.set_http_auth(('myuser', 'mypass')) mock_logger.reset_mock() res = g._ice_get('foobar') self.assertEquals(mock_logger.mock_calls, [call.debug('GETing http://foo.com/dashboard/foobar')] ) self.assertEquals(mock_requests.mock_calls, [ call.get('http://foo.com/dashboard/foobar', auth=('myuser', 'mypass')), call.get().json() ]) self.assertEquals(res, ['foo', 'bar'])
def test_ice_get_request_error(self, mock_requests, mock_logger): url = 'http://foo.com/dashboard/foobar' mock_result = Mock(status_code=502) mock_requests.get.return_value = mock_result g = Groups('http://foo.com/', dry_run=False) mock_logger.reset_mock() self.assertRaises(APIRequestException, g._ice_get, 'foobar') self.assertEquals(mock_logger.mock_calls, [call.debug('GETing http://foo.com/dashboard/foobar')]) self.assertEquals(mock_requests.mock_calls, [call.get('http://foo.com/dashboard/foobar', auth=None)])
def test_get_fortune_request_timeout(self): session = MagicMock() session.get.side_effect = ReadTimeout('request timed out') self._subject._session.__enter__.return_value = session assert_that(calling(self._subject.get_fortune), raises(FortuneRequestFailed)) assert_that(session.mock_calls, equal_to([call.get(self._subject._api_url)])) assert_that(self._subject._last_request, equal_to(None))
def test_read_config_gets_all_members_except_device( self, mock_eval, mock_setattr): eval_value = mock_eval.return_value mock_configparser = Mock() self.config.read_config(mock_configparser) for member in self.config.members(): if member != '_device': mock_configparser.get.assert_any_call(self.section, member) mock_setattr.assert_any_call(member, eval_value) device_call = call.get(self.section, '_device') assert device_call not in mock_configparser.mock_calls
def test_read_config_gets_all_members_except_device(self, mock_eval, mock_setattr): eval_value = mock_eval.return_value mock_configparser = Mock() self.config.read_config(mock_configparser) for member in self.config.members(): if member != '_device': mock_configparser.get.assert_any_call( self.section, member) mock_setattr.assert_any_call(member, eval_value) device_call = call.get(self.section, '_device') assert device_call not in mock_configparser.mock_calls
def test_maven_config_opt_adapter(self): """Test class MavenConfigOptAdapter""" conf = mock.MagicMock() section = 'section' adapter = koji.util.MavenConfigOptAdapter(conf, section) self.assertIs(adapter._conf, conf) self.assertIs(adapter._section, section) conf.has_option.return_value = True adapter.goals adapter.properties adapter.someattr conf.has_option.return_value = False with self.assertRaises(AttributeError) as cm: adapter.noexistsattr self.assertEquals(cm.exception.args[0], 'noexistsattr') self.assertEquals(conf.mock_calls, [call.has_option(section, 'goals'), call.get(section, 'goals'), call.get().split(), call.has_option(section, 'properties'), call.get(section, 'properties'), call.get().splitlines(), call.has_option(section, 'someattr'), call.get('section', 'someattr'), call.has_option(section, 'noexistsattr')])
def test__init__specifying_all__with_ssl(self): connection_params_dict_mock = RLockedMagicMock() connection_params_dict_mock.get.return_value = True self.meth.__init__(connection_params_dict=connection_params_dict_mock, exchange={ 'exchange': sen.exchange, 'foo': sen.foo }, queues_to_declare=sen.queues_to_declare, serialize=sen.serialize, prop_kwargs=sen.prop_kwargs, mandatory=sen.mandatory, output_fifo_max_size=12345, error_callback=sen.error_callback) # attrs self.assertIs(self.mock._connection_params_dict, connection_params_dict_mock) self.assertEqual(self.mock._exchange, { 'exchange': sen.exchange, 'foo': sen.foo }) self.assertEqual(self.mock._exchange_name, sen.exchange) self.assertEqual(self.mock._queues_to_declare, [ { 'queue': sen.queues_to_declare, 'callback': ANY }, ]) self.assertEqual(self.mock._serialize, sen.serialize) self.assertEqual(self.mock._prop_kwargs, sen.prop_kwargs) self.assertEqual(self.mock._mandatory, sen.mandatory) self.assertIs(self.mock._output_fifo.__class__, Queue.Queue) self.assertEqual(self.mock._output_fifo.maxsize, 12345) self.assertEqual(self.mock._error_callback, sen.error_callback) # calls self.assertEqual(self.mock.mock_calls, [ call._setup_communication(), call._start_publishing(), ]) self.assertEqual(connection_params_dict_mock.mock_calls, [ call.get('ssl'), call.setdefault('credentials', ANY), ]) self.assertIsInstance( connection_params_dict_mock.setdefault.mock_calls[0][-2] [1], # 2nd arg for setdefault pika.credentials.ExternalCredentials)
def test_get_metrics(self): # Slugs for metrics we want slugs = ['metric-1', 'metric-2'] # Build the various keys for each metric keys = [] for s in slugs: day, week, month, year = self.r._build_keys(s) keys.extend([day, week, month, year]) # construct the calls to redis calls = [call.get(k) for k in keys] # Test our method self.r.get_metrics(slugs) self.redis.assert_has_calls(calls)
def test_get_metric(self): """Tests getting a single metric; ``R.get_metric``.""" slug = 'test-metric' self.r.get_metric(slug) # Verify that we GET the keys from redis sec, min, hour, day, week, month, year = self.r._build_keys(slug) self.redis.assert_has_calls([ call.get(sec), call.get(min), call.get(hour), call.get(day), call.get(week), call.get(month), call.get(year), ])
def test_get_fortune_request_404(self): response = MagicMock() response.status_code = 404 response.content = b"URL not found" session = MagicMock() session.get.return_value = response self._subject._session.__enter__.return_value = session assert_that( calling(self._subject.get_fortune).with_args(now=_TEST_TIMESTAMP), raises(FortuneRequestFailed)) assert_that(session.mock_calls, equal_to([call.get(self._subject._api_url)])) assert_that(self._subject._last_request, equal_to(_TEST_TIMESTAMP))
def test_open(self, serial): self._subject._start_queue = MagicMock() self._subject.start = MagicMock() self._subject.open() assert_that( self._subject._start_queue.mock_calls, equal_to([ call.get() ]) ) assert_that( self._subject.start.mock_calls, equal_to([ call() ]) )
def test_get_fortune_pass(self): response = MagicMock() response.status_code = 200 response.content = _TEST_RAW_DATA session = MagicMock() session.get.return_value = response self._subject._session.__enter__.return_value = session # one call to the get_fortune method assert_that(self._subject.get_fortune(now=_TEST_TIMESTAMP), equal_to(_TEST_DECODED_DATA)) # results in one call to the Session assert_that(session.mock_calls, equal_to([call.get(self._subject._api_url)])) # and recording of the timestamp the call was made assert_that(self._subject._last_request, equal_to(_TEST_TIMESTAMP))
def test_login(): try: # Test that we fail gracefully with wrong user assert_raises(SynapseAuthenticationError, syn.login, str(uuid.uuid1()), 'notarealpassword') config = configparser.ConfigParser() config.read(client.CONFIG_FILE) username = config.get('authentication', 'username') password = config.get('authentication', 'password') sessionToken = syn._getSessionToken(username, password) # Simple login with ID + PW syn.login(username, password, silent=True) # Login with ID + API key syn.login(email=username, apiKey=base64.b64encode(syn.apiKey), silent=True) syn.logout(forgetMe=True) # Config file is read-only for the client, so it must be mocked! if (sys.version < '3'): configparser_package_name = 'ConfigParser' else: configparser_package_name = 'configparser' with patch("%s.ConfigParser.items" % configparser_package_name) as config_items_mock, patch("synapseclient.Synapse._readSessionCache") as read_session_mock: config_items_mock.return_value = [] read_session_mock.return_value = {} # Login with given bad session token, # It should REST PUT the token and fail # Then keep going and, due to mocking, fail to read any credentials assert_raises(SynapseAuthenticationError, syn.login, sessionToken="Wheeeeeeee") assert_false(config_items_mock.called) # Login with no credentials assert_raises(SynapseAuthenticationError, syn.login) config_items_mock.reset_mock() # Login with a session token from the config file config_items_mock.return_value = [('sessiontoken', sessionToken)] syn.login(silent=True) # Login with a bad session token from the config file config_items_mock.return_value = [('sessiontoken', "derp-dee-derp")] assert_raises(SynapseAuthenticationError, syn.login) # Login with session token syn.login(sessionToken=sessionToken, rememberMe=True, silent=True) # Login as the most recent user with patch('synapseclient.Synapse._readSessionCache') as read_session_mock: dict_mock = MagicMock() read_session_mock.return_value = dict_mock #first call is for <mostRecent> next call is the api key of the username in <mostRecent> dict_mock.get.side_effect = [syn.username, base64.b64encode(syn.apiKey)] syn.login(silent=True) dict_mock.assert_has_calls([call.get('<mostRecent>', None),call.get(syn.username, None)]) # Login with ID only syn.login(username, silent=True) syn.logout(forgetMe=True) except configparser.Error: print("To fully test the login method, please supply a username and password in the configuration file") finally: # Login with config file syn.login(rememberMe=True, silent=True)
def test_get_webservice_port(self): self.config_parser.get.return_value = 1234 assert_that(self.config.get_webservice_port()).is_equal_to(1234) assert_that(self.config_parser.mock_calls).contains(call.get('webservice', 'port'))
def test_get_username(self): self.config_parser.get.return_value = '<username>' assert_that(self.config.get_username()).is_equal_to('<username>') assert_that(self.config_parser.mock_calls).contains(call.get('auth', 'username'))
def get(self, url, *args, **kwargs): updated_kwargs = self._update_headers(kwargs) self.calls.append(call.get(url, *args, **updated_kwargs)) return _RequestContextManager(self._get_stored_value(url, "get"))
def test_get_gauge(self): """Tests retrieving a gague with ``R.get_gauge``. Verifies that the Redis GET command is called with the correct key.""" self.r.get_gauge('test-gauge') self.redis.assert_has_calls([call.get('g:test-gauge')])
def test__init__specifying_all_and_obtaining_global_conn_params__with_ssl( self): connection_params_dict_mock = RLockedMagicMock() connection_params_dict_mock.get.return_value = True with rlocked_patch( 'n6lib.amqp_getters_pushers.get_amqp_connection_params_dict', **{'return_value': connection_params_dict_mock}) as get_amqp_conn_params_mock: self.meth.__init__(connection_params_dict=None, exchange={ 'exchange': sen.exchange, 'bar': sen.bar }, queues_to_declare=[ sen.queue1, { 'blabla': sen.blabla }, { 'blabla': sen.blabla, 'callback': sen.callback }, ], serialize=sen.serialize, prop_kwargs=sen.prop_kwargs, mandatory=sen.mandatory, output_fifo_max_size=54321, error_callback=sen.error_callback) # attrs self.assertIs(self.mock._connection_params_dict, connection_params_dict_mock) self.assertEqual(self.mock._exchange, { 'exchange': sen.exchange, 'bar': sen.bar }) self.assertEqual(self.mock._exchange_name, sen.exchange) self.assertEqual(self.mock._queues_to_declare, [ { 'queue': sen.queue1, 'callback': ANY }, { 'blabla': sen.blabla, 'callback': ANY }, { 'blabla': sen.blabla, 'callback': sen.callback }, ]) self.assertEqual(self.mock._serialize, sen.serialize) self.assertEqual(self.mock._prop_kwargs, sen.prop_kwargs) self.assertEqual(self.mock._mandatory, sen.mandatory) self.assertIs(self.mock._output_fifo.__class__, Queue.Queue) self.assertEqual(self.mock._output_fifo.maxsize, 54321) self.assertEqual(self.mock._error_callback, sen.error_callback) # calls self.assertEqual(self.mock.mock_calls, [ call._setup_communication(), call._start_publishing(), ]) self.assertEqual(get_amqp_conn_params_mock.mock_calls, [ call(), ]) self.assertEqual(connection_params_dict_mock.mock_calls, [ call.get('ssl'), call.setdefault('credentials', ANY), ]) self.assertIsInstance( connection_params_dict_mock.setdefault.mock_calls[0][-2] [1], # 2nd arg for setdefault pika.credentials.ExternalCredentials)
def test_get_webservice_port(self): self.config_parser.get.return_value = 1234 assert_that(self.config.get_webservice_port(), is_(equal_to(1234))) assert_that(self.config_parser.mock_calls, contains(call.get('webservice', 'port')))
def test_get_archive_path(self): self.config_parser.get.return_value = '<archive_path>' assert_that(self.config.get_archive_path()).is_equal_to('<archive_path>') assert_that(self.config_parser.mock_calls).contains(call.get('path', 'archive'))
def test_comment_on_pr(self, mock_getenv, mock_client_session): mock_args, fake_client_session = self.create_mock_pr( mock_getenv, mock_client_session) reporter = github_reporter.create_reporter(mock_args) async_report = reporter.report([ Problem('some_dir/some_file', 40, 'this made me sad'), Problem('some_dir/some_file', 40, 'really sad'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 3, 'I am a duplicate!'), Problem('missing_file', 42, "Don't report me!!!"), ]) loop = asyncio.get_event_loop() loop.run_until_complete(async_report) diff_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234', headers={ 'Accept': 'application/vnd.github.diff', 'Authorization': 'token MY_TOKEN' }) existing_comments_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}) first_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'commit_id': 'abc123', 'path': 'another_file', 'body': textwrap.dedent('''\ :sparkles:Linty Fresh Says:sparkles:: ``` This is OK ```'''), 'position': 2 }, sort_keys=True)) second_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'commit_id': 'abc123', 'path': 'some_dir/some_file', 'body': textwrap.dedent('''\ :sparkles:Linty Fresh Says:sparkles:: ``` this made me sad really sad ```'''), 'position': 3 }, sort_keys=True)) self.assertEqual(4, len(fake_client_session.calls)) self.assertIn(diff_request, fake_client_session.calls) self.assertIn(existing_comments_request, fake_client_session.calls) self.assertIn(first_comment, fake_client_session.calls) self.assertIn(second_comment, fake_client_session.calls)
def test_get_username(self): self.config_parser.get.return_value = '<username>' assert_that(self.config.get_username(), is_(equal_to('<username>'))) assert_that(self.config_parser.mock_calls, contains(call.get('auth', 'username')))
def test_comment_on_pr(self, mock_getenv, mock_client_session): mock_args, fake_client_session = self.create_mock_pr( mock_getenv, mock_client_session) reporter = github_reporter.create_reporter(mock_args) async_report = reporter.report('unit-test-linter', [ Problem('some_dir/some_file', 40, 'this made me sad'), Problem('some_dir/some_file', 40, 'really sad'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 3, 'I am a duplicate!'), Problem('another_file', 52, "#close_enough!!!"), Problem('missing_file', 42, "Missing file comment!!!"), ]) loop = asyncio.get_event_loop() loop.run_until_complete(async_report) diff_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234', headers={ 'Accept': 'application/vnd.github.diff', 'Authorization': 'token MY_TOKEN' }) existing_comments_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}) first_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'commit_id': 'abc123', 'path': 'another_file', 'body': textwrap.dedent('''\ unit-test-linter says: ``` This is OK ```'''), 'position': 2 }, sort_keys=True)) second_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'commit_id': 'abc123', 'path': 'some_dir/some_file', 'body': textwrap.dedent('''\ unit-test-linter says: ``` this made me sad really sad ```'''), 'position': 3 }, sort_keys=True)) close_enough_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'commit_id': 'abc123', 'path': 'another_file', 'body': textwrap.dedent('''\ unit-test-linter says: (From line 52) ``` #close_enough!!! ```'''), 'position': 12 }, sort_keys=True)) missing_file_call = call.post( 'https://api.github.com/repos/foo/bar/issues/1234/comments', headers={'Authorization': 'token MY_TOKEN'}, data=json.dumps( { 'body': textwrap.dedent('''\ unit-test-linter found some problems with lines not modified by this commit: ``` missing_file:42: \tMissing file comment!!! ```'''), }, sort_keys=True)) self.assertEqual(6, len(fake_client_session.calls)) self.assertIn(diff_request, fake_client_session.calls) self.assertIn(existing_comments_request, fake_client_session.calls) self.assertIn(first_comment, fake_client_session.calls) self.assertIn(second_comment, fake_client_session.calls) self.assertIn(close_enough_comment, fake_client_session.calls) self.assertIn(missing_file_call, fake_client_session.calls)
def test_get_password(self): self.config_parser.get.return_value = '<password>' assert_that(self.config.get_password(), is_(equal_to('<password>'))) assert_that(self.config_parser.mock_calls, contains(call.get('auth', 'password')))
def test_get_archive_path(self): self.config_parser.get.return_value = '<archive_path>' assert_that(self.config.get_archive_path(), is_(equal_to('<archive_path>'))) assert_that(self.config_parser.mock_calls, contains(call.get('path', 'archive')))
def test_get_password(self): self.config_parser.get.return_value = '<password>' assert_that(self.config.get_password()).is_equal_to('<password>') assert_that(self.config_parser.mock_calls).contains(call.get('auth', 'password'))
def get(self, url, *args, **kwargs): updated_kwargs = self._update_headers(kwargs) self.calls.append(call.get(url, *args, **updated_kwargs)) return _RequestContextManager(self._get_stored_value(url, 'get'))
def test_comment_on_pr(self, mock_getenv, mock_client_session): mock_args, fake_client_session = self.create_mock_pr( mock_getenv, mock_client_session) reporter = github_reporter.create_reporter(mock_args) async_report = reporter.report([ Problem('some_dir/some_file', 40, 'this made me sad'), Problem('some_dir/some_file', 40, 'really sad'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 2, 'This is OK'), Problem('another_file', 3, 'I am a duplicate!'), Problem('missing_file', 42, "Don't report me!!!"), ]) loop = asyncio.get_event_loop() loop.run_until_complete(async_report) diff_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234', headers={ 'Accept': 'application/vnd.github.diff', 'Authorization': 'token MY_TOKEN' }) existing_comments_request = call.get( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={ 'Authorization': 'token MY_TOKEN' }) first_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={ 'Authorization': 'token MY_TOKEN' }, data=json.dumps({ 'commit_id': 'abc123', 'path': 'another_file', 'body': textwrap.dedent('''\ :sparkles:Linty Fresh Says:sparkles:: ``` This is OK ```'''), 'position': 2 }, sort_keys=True) ) second_comment = call.post( 'https://api.github.com/repos/foo/bar/pulls/1234/comments', headers={ 'Authorization': 'token MY_TOKEN' }, data=json.dumps({ 'commit_id': 'abc123', 'path': 'some_dir/some_file', 'body': textwrap.dedent('''\ :sparkles:Linty Fresh Says:sparkles:: ``` this made me sad really sad ```'''), 'position': 3 }, sort_keys=True) ) self.assertEqual(4, len(fake_client_session.calls)) self.assertIn(diff_request, fake_client_session.calls) self.assertIn(existing_comments_request, fake_client_session.calls) self.assertIn(first_comment, fake_client_session.calls) self.assertIn(second_comment, fake_client_session.calls)