def test_assert_has_calls(self): kalls1 = [call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6})] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in (Mock(), MagicMock()): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in (1, 2, 3): these = kalls[i:i + step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises(AssertionError, mock. assert_has_calls, list(reversed(these)))
def test_variable_timeouts(self): nt = {"https://google.com/timeout/test/2/3/4/5/something": 10, "https://facebook.com/timeout": 15} file_contents = """ https://facebook.com/ https://google.com/ https://coala.io/som/thingg/page/123 """.splitlines() def response(status_code, *args, **kwargs): res = requests.Response() res.status_code = status_code return res with unittest.mock.patch( "tests.general.InvalidLinkBearTest.requests.head", return_value=response(status_code=200) ) as mock: uut = InvalidLinkBear(self.section, Queue()) self.assertEqual([x.message for x in list(uut.run("file", file_contents, network_timeout=nt))], []) mock.assert_has_calls( [ unittest.mock.call("https://facebook.com/", timeout=15, allow_redirects=False), unittest.mock.call("https://google.com/", timeout=10, allow_redirects=False), unittest.mock.call("https://coala.io/som/thingg/page/123", timeout=2, allow_redirects=False), ] )
def test_assert_has_calls(self): kalls1 = [call(1, 2), ({"a": 3},), ((3, 4),), call(b=6), ("", (1,), {"b": 6})] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i : i + step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises(AssertionError, mock.assert_has_calls, list(reversed(these)))
def test_password_prompt(self): from io import StringIO import agutil.security.console password = make_random_string() mock = unittest.mock.create_autospec(agutil.security.console.getpass, return_value=password) agutil.security.console.getpass = mock source = tempname() encrypted = tempname() decrypted = tempname() writer = open(source, mode='w') for line in range(15): writer.write(make_random_string()) writer.write('\n') writer.close() agutil.security.console.main([ 'encrypt', source, '-o', encrypted ]) self.assertFalse(cmp(source, encrypted)) agutil.security.console.main([ 'decrypt', encrypted, '-o', decrypted ]) self.assertTrue(cmp(source, decrypted)) mock.assert_has_calls([ unittest.mock.call('Encryption password: '******'Confirm password: '******'Decryption password: ') ])
def test_variable_timeouts(self): nt = { 'https://google.com/timeout/test/2/3/4/5/something': 10, 'https://facebook.com/timeout': 2, '*': 25 } file_contents = """ https://facebook.com/ https://google.com/ https://coala.io/som/thingg/page/123 """.splitlines() def response(status_code, *args, **kwargs): res = requests.Response() res.status_code = status_code return res with unittest.mock.patch( 'tests.general.InvalidLinkBearTest.requests.head', return_value=response(status_code=200)) as mock: self.check_validity(self.uut, file_contents, settings={'network_timeout': nt}) with self.assertLogs(logging.getLogger()) as log: self.check_validity(self.uut, file_contents, settings={'timeout': 20}) self.assertEqual(log.output, [ 'WARNING:root:The setting `timeout` is ' 'deprecated. Please use `network_timeout` ' 'instead.' ]) self.check_validity(self.uut, ['https://gitmate.io']) mock.assert_has_calls([ unittest.mock.call('https://facebook.com/', timeout=2, allow_redirects=False), unittest.mock.call('https://google.com/', timeout=10, allow_redirects=False), unittest.mock.call('https://coala.io/som/thingg/page/123', timeout=25, allow_redirects=False), unittest.mock.call('https://facebook.com/', timeout=20, allow_redirects=False), unittest.mock.call('https://google.com/', timeout=20, allow_redirects=False), unittest.mock.call('https://coala.io/som/thingg/page/123', timeout=20, allow_redirects=False), unittest.mock.call('https://gitmate.io', timeout=15, allow_redirects=False) ])
def test_process_stops(self, mock): expected_calls = [unittest.mock.call(stop) for stop in self.STOPS] fetcher = ScheduleFetcher(api_key='foo') fetcher.process_stops( stops=[self.denormalize(data) for data in self.STOPS]) mock.assert_has_calls(expected_calls) assert mock.call_count == len(expected_calls)
def test_variable_timeouts(self): nt = { 'https://google.com/timeout/test/2/3/4/5/something': 10, 'https://facebook.com/timeout': 2, '*': 25 } file_contents = """ https://facebook.com/ https://google.com/ https://coala.io/som/thingg/page/123 """.splitlines() def response(status_code, *args, **kwargs): res = requests.Response() res.status_code = status_code return res with unittest.mock.patch( 'tests.general.InvalidLinkBearTest.requests.head', return_value=response(status_code=200)) as mock: uut = InvalidLinkBear(self.section, Queue()) self.assertEqual([x.message for x in list(uut.run('file', file_contents, network_timeout=nt))], []) with self.assertLogs(logging.getLogger()) as log: self.assertEqual([x.message for x in list(uut.run('file', file_contents, timeout=20))], []) self.assertEqual(log.output, ['WARNING:root:The setting `timeout` is ' 'deprecated. Please use `network_timeout` ' 'instead.']) self.assertEqual([x.message for x in list(uut.run('file', ['https://gitmate.io']))], []) mock.assert_has_calls([ unittest.mock.call('https://facebook.com/', timeout=2, allow_redirects=False), unittest.mock.call('https://google.com/', timeout=10, allow_redirects=False), unittest.mock.call('https://coala.io/som/thingg/page/123', timeout=25, allow_redirects=False), unittest.mock.call('https://facebook.com/', timeout=20, allow_redirects=False), unittest.mock.call('https://google.com/', timeout=20, allow_redirects=False), unittest.mock.call('https://coala.io/som/thingg/page/123', timeout=20, allow_redirects=False), unittest.mock.call('https://gitmate.io', timeout=15, allow_redirects=False)])
def test_process_lines(self, mock): expected_calls = [ unittest.mock.call(line, self.STOPS[0]) for line in self.LINES ] fetcher = ScheduleFetcher(api_key='foo') fetcher.process_lines( lines=[self.denormalize(data) for data in self.LINES], stop=self.STOPS[0]) mock.assert_has_calls(expected_calls) assert mock.call_count == len(expected_calls)
def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({ 'a': 3 }, ), ((3, 4), ), ((), { 'a': 3 }), ('', (1, 2)), ('', { 'a': 3 }), ('', (1, 2), {}), ('', (), { 'a': 3 }) ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': self.assertRaises(AssertionError, mock.assert_has_calls, [kall], any_order=True) kall_lists = [ [call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)], ] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises(AssertionError, mock.assert_has_calls, kall_list, any_order=True)
def test_shutdown(self): valid_wrapper_2 = deepcopy(self.valid_wrapper) valid_wrapper_2["payload"]["result"]["hello"] = 25 valid_wrapper_3 = deepcopy(self.valid_wrapper) valid_wrapper_3["payload"]["result"]["hello"] = 5000 self.producer.produce(self.topic, json.dumps(self.valid_wrapper)) self.producer.produce(self.topic, json.dumps(valid_wrapper_2)) self.producer.produce(self.topic, json.dumps(valid_wrapper_3)) self.producer.flush() def normalize_payload(payload): return { **payload, "values": payload["result"], "timestamp": parse_date(payload["timestamp"]).replace(tzinfo=pytz.utc), } consumer = QuerySubscriptionConsumer("hi", topic=self.topic, commit_batch_size=100) def mock_callback(*args, **kwargs): if mock.call_count >= len(expected_calls): consumer.shutdown() mock = Mock(side_effect=mock_callback) register_subscriber(self.registration_key)(mock) sub = self.create_subscription() expected_calls = [ call(normalize_payload(self.valid_payload), sub), call(normalize_payload(valid_wrapper_2["payload"]), sub), ] consumer.run() mock.assert_has_calls(expected_calls) expected_calls = [ call(normalize_payload(valid_wrapper_3["payload"]), sub) ] mock.reset_mock() consumer.run() mock.assert_has_calls(expected_calls)
def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3})] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in (call(1, '2'), call(b=3), call(), 3, None, 'foo'): self.assertRaises(AssertionError, mock.assert_has_calls, [kall], any_order=True) kall_lists = [[call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)]] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [[call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)]] for kall_list in kall_lists: self.assertRaises(AssertionError, mock.assert_has_calls, kall_list, any_order=True)
def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({"a": 3},), ((3, 4),), ((), {"a": 3}), ("", (1, 2)), ("", {"a": 3}), ("", (1, 2), {}), ("", (), {"a": 3}), ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, "2"), call(b=3), call(), 3, None, "foo": self.assertRaises(AssertionError, mock.assert_has_calls, [kall], any_order=True) kall_lists = [[call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)]] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises(AssertionError, mock.assert_has_calls, kall_list, any_order=True)
def test_variable_timeouts(self): nt = { 'https://google.com/timeout/test/2/3/4/5/something': 10, 'https://facebook.com/timeout': 2 } file_contents = """ https://facebook.com/ https://google.com/ https://coala.io/som/thingg/page/123 """.splitlines() def response(status_code, *args, **kwargs): res = requests.Response() res.status_code = status_code return res with unittest.mock.patch( 'tests.general.InvalidLinkBearTest.requests.head', return_value=response(status_code=200)) as mock: uut = InvalidLinkBear(self.section, Queue()) self.assertEqual([ x.message for x in list( uut.run('file', file_contents, network_timeout=nt)) ], []) mock.assert_has_calls([ unittest.mock.call('https://facebook.com/', timeout=2, allow_redirects=False), unittest.mock.call('https://google.com/', timeout=10, allow_redirects=False), unittest.mock.call('https://coala.io/som/thingg/page/123', timeout=15, allow_redirects=False) ])
def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), {'d': 7}), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True)
def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), { 'd': 7 }), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True)
def _assert_calls(self, mock, expected_calls): self.assertEqual(len(expected_calls), mock.call_count) mock.assert_has_calls(expected_calls, any_order=True)