diff --git a/.coveragerc b/.coveragerc index ce326524..c8507fe7 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,4 +5,5 @@ omit = autopush/gcdump.py autopush/webpush_server.py autopush/tests/test_webpush_server.py + autopush/tests/conftest.py show_missing = true diff --git a/autopush/db.py b/autopush/db.py index bdef0ea5..83a8b390 100644 --- a/autopush/db.py +++ b/autopush/db.py @@ -504,7 +504,7 @@ def fetch_messages( def fetch_timestamp_messages( self, uaid, # type: uuid.UUID - timestamp=None, # type: Optional[int] + timestamp=None, # type: Optional[int or str] limit=10, # type: int ): # type: (...) -> Tuple[Optional[int], List[WebPushNotification]] diff --git a/autopush/tests/conftest.py b/autopush/tests/conftest.py new file mode 100644 index 00000000..f6c98858 --- /dev/null +++ b/autopush/tests/conftest.py @@ -0,0 +1,11 @@ +from autopush.tests import setUp, tearDown + + +def pytest_configure(config): + """Called before testing begins""" + setUp() + + +def pytest_unconfigure(config): + """Called after all tests run and warnings displayed""" + tearDown() diff --git a/autopush/tests/test_cryptokey.py b/autopush/tests/test_cryptokey.py index 470e594e..1581e32b 100644 --- a/autopush/tests/test_cryptokey.py +++ b/autopush/tests/test_cryptokey.py @@ -1,6 +1,6 @@ import unittest -from nose.tools import (eq_, ok_, assert_raises) +import pytest from autopush.crypto_key import CryptoKey, CryptoKeyException @@ -15,47 +15,47 @@ class CryptoKeyTestCase(unittest.TestCase): def test_parse(self): ckey = CryptoKey(self.valid_key) - eq_(ckey.get_keyid("p256dh"), - {"keyid": "p256dh", - "dh": "BDw9T0eImd4ax818VcYqDK_DOhcuDswKero" - "YyNkdhYmygoLSDlSiWpuoWYUSSFxi25cyyNTR5k9Ny93DzZc0UI4"}) - eq_(ckey.get_label("p256ecdsa"), + assert ckey.get_keyid("p256dh") == { + "keyid": "p256dh", + "dh": "BDw9T0eImd4ax818VcYqDK_DOhcuDswKero" + "YyNkdhYmygoLSDlSiWpuoWYUSSFxi25cyyNTR5k9Ny93DzZc0UI4"} + assert ckey.get_label("p256ecdsa") == ( "BF92zdI_AKcH5Q31_Rr-04bPqOHU_Qg6lAawHbvfQrY" "xV_vIsAsHSyaiuyfofvxT8ZVIXccykd4V2Z7iJVfreT8") - ok_(ckey.get_keyid("missing") is None) - ok_(ckey.get_label("missing") is None) + assert ckey.get_keyid("missing") is None + assert ckey.get_label("missing") is None def test_parse_and_get_label(self): - eq_(CryptoKey.parse_and_get_label(self.valid_key, "p256ecdsa"), + assert CryptoKey.parse_and_get_label(self.valid_key, "p256ecdsa") == ( "BF92zdI_AKcH5Q31_Rr-04bPqOHU_Qg6lAawHbvfQrY" "xV_vIsAsHSyaiuyfofvxT8ZVIXccykd4V2Z7iJVfreT8") - ok_(CryptoKey.parse_and_get_label(self.valid_key, "missing") is None) - ok_(CryptoKey.parse_and_get_label("invalid key", "missing") is None) + assert CryptoKey.parse_and_get_label(self.valid_key, "missing") is None + assert CryptoKey.parse_and_get_label("invalid key", "missing") is None def test_parse_invalid(self): - with assert_raises(CryptoKeyException) as ex: + with pytest.raises(CryptoKeyException) as ex: CryptoKey("invalid key") - eq_(ex.exception.message, "Invalid Crypto Key value") + assert ex.value.message == "Invalid Crypto Key value" def test_parse_different_order(self): ckey = CryptoKey(self.valid_key) ckey2 = CryptoKey(','.join(self.valid_key.split(',')[::-1])) - ok_(ckey.get_keyid("p256dh"), ckey2.get_keyid("p256dh")) - ok_(ckey.get_label("p256ecdsa") is not None) - ok_(ckey.get_label("p256ecdsa"), ckey2.get_label("p256ecdsa")) + assert ckey.get_keyid("p256dh") == ckey2.get_keyid("p256dh") + assert ckey.get_label("p256ecdsa") is not None + assert ckey.get_label("p256ecdsa") == ckey2.get_label("p256ecdsa") def test_parse_lenient(self): ckey = CryptoKey(self.valid_key.replace('"', '')) str = ckey.to_string() ckey2 = CryptoKey(str) - ok_(ckey.get_keyid("p256dh"), ckey2.get_keyid("p256dh")) - ok_(ckey.get_label("p256ecdsa") is not None) - ok_(ckey.get_label("p256ecdsa"), ckey2.get_label("p256ecdsa")) + assert ckey.get_keyid("p256dh") == ckey2.get_keyid("p256dh") + assert ckey.get_label("p256ecdsa") is not None + assert ckey.get_label("p256ecdsa") == ckey2.get_label("p256ecdsa") def test_string(self): ckey = CryptoKey(self.valid_key) str = ckey.to_string() ckey2 = CryptoKey(str) - ok_(ckey.get_keyid("p256dh"), ckey2.get_keyid("p256dh")) - ok_(ckey.get_label("p256ecdsa") is not None) - ok_(ckey.get_label("p256ecdsa"), ckey2.get_label("p256ecdsa")) + assert ckey.get_keyid("p256dh") == ckey2.get_keyid("p256dh") + assert ckey.get_label("p256ecdsa") is not None + assert ckey.get_label("p256ecdsa") == ckey2.get_label("p256ecdsa") diff --git a/autopush/tests/test_db.py b/autopush/tests/test_db.py index 663595b7..cd6c71df 100644 --- a/autopush/tests/test_db.py +++ b/autopush/tests/test_db.py @@ -11,7 +11,7 @@ from boto.dynamodb2.layer1 import DynamoDBConnection from boto.dynamodb2.items import Item from mock import Mock -from nose.tools import eq_, assert_raises, ok_ +import pytest from autopush.db import ( get_rotating_message_table, @@ -54,7 +54,7 @@ def raise_exc(*args, **kwargs): # pragma: no cover router.clear_node = Mock() router.clear_node.side_effect = raise_exc - with assert_raises(Exception): + with pytest.raises(Exception): preflight_check(message, router) def test_preflight_check(self): @@ -65,8 +65,9 @@ def test_preflight_check(self): preflight_check(message, router, pf_uaid) # now check that the database reports no entries. _, notifs = message.fetch_messages(uuid.UUID(pf_uaid)) - eq_(len(notifs), 0) - assert_raises(ItemNotFound, router.get_uaid, pf_uaid) + assert len(notifs) == 0 + with pytest.raises(ItemNotFound): + router.get_uaid(pf_uaid) def test_preflight_check_wait(self): router = Router(get_router_table(), SinkMetrics()) @@ -87,8 +88,9 @@ def return_vals(*args, **kwargs): preflight_check(message, router, pf_uaid) # now check that the database reports no entries. _, notifs = message.fetch_messages(uuid.UUID(pf_uaid)) - eq_(len(notifs), 0) - assert_raises(ItemNotFound, router.get_uaid, pf_uaid) + assert len(notifs) == 0 + with pytest.raises(ItemNotFound): + router.get_uaid(pf_uaid) def test_get_month(self): from autopush.db import get_month @@ -96,19 +98,19 @@ def test_get_month(self): month1 = get_month(1) this_month = month0.month next_month = 1 if this_month == 12 else this_month + 1 - eq_(next_month, month1.month) + assert next_month == month1.month def test_zero_fill_month(self): from autopush.db import make_rotating_tablename - eq_('test_2016_03', - make_rotating_tablename('test', date=datetime(2016, 3, 15))) + assert 'test_2016_03' == make_rotating_tablename( + 'test', date=datetime(2016, 3, 15).date()) def test_hasher(self): import autopush.db as db db.key_hash = "SuperSikkret" v = db.hasher("01234567123401234123456789ABCDEF") - eq_(v, '0530bb351921e7b4be66831e4c126c6' + - 'd8f614d06cdd592cb8470f31177c8331a') + assert v == ('0530bb351921e7b4be66831e4c126c6' + 'd8f614d06cdd592cb8470f31177c8331a') db.key_hash = "" def test_normalize_id(self): @@ -116,9 +118,10 @@ def test_normalize_id(self): import autopush.db as db abnormal = "deadbeef00000000decafbad00000000" normal = "deadbeef-0000-0000-deca-fbad00000000" - eq_(db.normalize_id(abnormal), normal) - assert_raises(ValueError, db.normalize_id, "invalid") - eq_(db.normalize_id(abnormal.upper()), normal) + assert db.normalize_id(abnormal) == normal + with pytest.raises(ValueError): + db.normalize_id("invalid") + assert db.normalize_id(abnormal.upper()) == normal class MessageTestCase(unittest.TestCase): @@ -140,7 +143,7 @@ def test_register(self): # Verify its in the db rows = m.query_2(uaid__eq=self.uaid, chidmessageid__eq=" ") results = list(rows) - eq_(len(results), 1) + assert len(results) == 1 def test_unregister(self): chid = str(uuid.uuid4()) @@ -151,16 +154,16 @@ def test_unregister(self): # Verify its in the db rows = m.query_2(uaid__eq=self.uaid, chidmessageid__eq=" ") results = list(rows) - eq_(len(results), 1) - eq_(results[0]["chids"], set([chid])) + assert len(results) == 1 + assert results[0]["chids"] == {chid} message.unregister_channel(self.uaid, chid) # Verify its not in the db rows = m.query_2(uaid__eq=self.uaid, chidmessageid__eq=" ") results = list(rows) - eq_(len(results), 1) - eq_(results[0]["chids"], None) + assert len(results) == 1 + assert results[0]["chids"] is None # Test for the very unlikely case that there's no 'chid' m.connection.update_item = Mock() @@ -168,7 +171,7 @@ def test_unregister(self): 'Attributes': {'uaid': {'S': self.uaid}}, 'ConsumedCapacityUnits': 0.5} r = message.unregister_channel(self.uaid, dummy_chid) - eq_(r, False) + assert r is False def test_all_channels(self): chid = str(uuid.uuid4()) @@ -179,13 +182,13 @@ def test_all_channels(self): message.register_channel(self.uaid, chid2) _, chans = message.all_channels(self.uaid) - ok_(chid in chans) - ok_(chid2 in chans) + assert chid in chans + assert chid2 in chans message.unregister_channel(self.uaid, chid2) _, chans = message.all_channels(self.uaid) - ok_(chid2 not in chans) - ok_(chid in chans) + assert chid2 not in chans + assert chid in chans def test_save_channels(self): chid = str(uuid.uuid4()) @@ -199,13 +202,13 @@ def test_save_channels(self): new_uaid = uuid.uuid4().hex message.save_channels(new_uaid, chans) _, new_chans = message.all_channels(new_uaid) - eq_(chans, new_chans) + assert chans == new_chans def test_all_channels_no_uaid(self): m = get_rotating_message_table() message = Message(m, SinkMetrics()) exists, chans = message.all_channels(dummy_uaid) - eq_(chans, set([])) + assert chans == set([]) def test_message_storage(self): chid = str(uuid.uuid4()) @@ -221,7 +224,7 @@ def test_message_storage(self): _, all_messages = message.fetch_timestamp_messages( uuid.UUID(self.uaid), " ") - eq_(len(all_messages), 3) + assert len(all_messages) == 3 def test_message_storage_overwrite(self): """Test that store_message can overwrite existing messages which @@ -242,7 +245,7 @@ def test_message_storage_overwrite(self): message.store_message(notif3) all_messages = list(message.fetch_messages(uuid.UUID(self.uaid))) - eq_(len(all_messages), 2) + assert len(all_messages) == 2 def test_message_delete_fail_condition(self): notif = make_webpush_notification(dummy_uaid, dummy_chid) @@ -256,24 +259,26 @@ def raise_condition(*args, **kwargs): message.table = Mock() message.table.delete_item.side_effect = raise_condition result = message.delete_message(notif) - eq_(result, False) + assert result is False def test_message_rotate_table_with_date(self): prefix = "message" + uuid.uuid4().hex - future = datetime.today() + timedelta(days=32) + future = (datetime.today() + timedelta(days=32)).date() tbl_name = make_rotating_tablename(prefix, date=future) m = get_rotating_message_table(prefix=prefix, date=future) - eq_(m.table_name, tbl_name) + assert m.table_name == tbl_name class RouterTestCase(unittest.TestCase): - def setUp(self): + @classmethod + def setup_class(self): table = get_router_table() self.real_table = table self.real_connection = table.connection - def tearDown(self): + @classmethod + def teardown_class(self): self.real_table.connection = self.real_connection def _create_minimal_record(self): @@ -293,27 +298,28 @@ def test_drop_old_users(self): router.register_user(self._create_minimal_record()) results = router.drop_old_users(months_ago=0) - eq_(list(results), [25, 25, 3]) + assert list(results) == [25, 25, 3] def test_custom_tablename(self): db = DynamoDBConnection() db_name = "router_%s" % uuid.uuid4() - ok_(not table_exists(db, db_name)) + assert not table_exists(db, db_name) create_router_table(db_name) - ok_(table_exists(db, db_name)) + assert table_exists(db, db_name) def test_provisioning(self): db_name = "router_%s" % uuid.uuid4() r = create_router_table(db_name, 3, 17) - eq_(r.throughput["read"], 3) - eq_(r.throughput["write"], 17) + assert r.throughput["read"] == 3 + assert r.throughput["write"] == 17 def test_no_uaid_found(self): uaid = str(uuid.uuid4()) r = get_router_table() router = Router(r, SinkMetrics()) - assert_raises(ItemNotFound, router.get_uaid, uaid) + with pytest.raises(ItemNotFound): + router.get_uaid(uaid) def test_uaid_provision_failed(self): r = get_router_table() @@ -324,7 +330,7 @@ def raise_error(*args, **kwargs): raise ProvisionedThroughputExceededException(None, None) router.table.get_item.side_effect = raise_error - with assert_raises(ProvisionedThroughputExceededException): + with pytest.raises(ProvisionedThroughputExceededException): router.get_uaid(uaid="asdf") def test_register_user_provision_failed(self): @@ -336,7 +342,7 @@ def raise_error(*args, **kwargs): raise ProvisionedThroughputExceededException(None, None) router.table.connection.update_item.side_effect = raise_error - with assert_raises(ProvisionedThroughputExceededException): + with pytest.raises(ProvisionedThroughputExceededException): router.register_user(dict(uaid=dummy_uaid, node_id="me", connected_at=1234, router_type="webpush")) @@ -350,7 +356,7 @@ def raise_error(*args, **kwargs): raise ProvisionedThroughputExceededException(None, None) router.table.connection.put_item.side_effect = raise_error - with assert_raises(ProvisionedThroughputExceededException): + with pytest.raises(ProvisionedThroughputExceededException): router.clear_node(Item(r, dict(uaid=dummy_uaid, connected_at="1234", node_id="asdf", @@ -369,8 +375,9 @@ def test_incomplete_uaid(self): router.register_user(dict(uaid=uaid)) except AutopushException: pass - assert_raises(ItemNotFound, router.get_uaid, uaid) - ok_(router.drop_user.called) + with pytest.raises(ItemNotFound): + router.get_uaid(uaid) + assert router.drop_user.called def test_save_new(self): r = get_router_table() @@ -382,7 +389,7 @@ def test_save_new(self): result = router.register_user(dict(uaid="", node_id="me", router_type="webpush", connected_at=1234)) - eq_(result[0], True) + assert result[0] is True def test_save_fail(self): r = get_router_table() @@ -396,7 +403,7 @@ def raise_condition(*args, **kwargs): router_data = dict(uaid=dummy_uaid, node_id="asdf", connected_at=1234, router_type="webpush") result = router.register_user(router_data) - eq_(result, (False, {})) + assert result == (False, {}) def test_node_clear(self): r = get_router_table() @@ -408,18 +415,18 @@ def test_node_clear(self): router_type="webpush")) # Verify user = router.get_uaid(dummy_uaid) - eq_(user["node_id"], "asdf") - eq_(user["connected_at"], 1234) - eq_(user["router_type"], "webpush") + assert user["node_id"] == "asdf" + assert user["connected_at"] == 1234 + assert user["router_type"] == "webpush" # Clear router.clear_node(user) # Verify user = router.get_uaid(dummy_uaid) - eq_(user.get("node_id"), None) - eq_(user["connected_at"], 1234) - eq_(user["router_type"], "webpush") + assert user.get("node_id") is None + assert user["connected_at"] == 1234 + assert user["router_type"] == "webpush" def test_node_clear_fail(self): r = get_router_table() @@ -432,7 +439,7 @@ def raise_condition(*args, **kwargs): router.table.connection.put_item.side_effect = raise_condition data = dict(uaid=dummy_uaid, node_id="asdf", connected_at=1234) result = router.clear_node(Item(r, data)) - eq_(result, False) + assert result is False def test_drop_user(self): uaid = str(uuid.uuid4()) @@ -443,7 +450,7 @@ def test_drop_user(self): router_type="webpush", connected_at=1234)) result = router.drop_user(uaid) - eq_(result, True) + assert result is True # Deleting already deleted record should return false. result = router.drop_user(uaid) - eq_(result, False) + assert result is False diff --git a/autopush/tests/test_diagnostic_cli.py b/autopush/tests/test_diagnostic_cli.py index 14f46ab6..9094f01e 100644 --- a/autopush/tests/test_diagnostic_cli.py +++ b/autopush/tests/test_diagnostic_cli.py @@ -1,7 +1,6 @@ import unittest from mock import Mock, patch -from nose.tools import eq_, ok_ class FakeDict(dict): @@ -18,7 +17,7 @@ def test_basic_load(self): "--router_tablename=fred", "http://someendpoint", ]) - eq_(cli.db.router.table.table_name, "fred") + assert cli.db.router.table.table_name == "fred" def test_bad_endpoint(self): cli = self._makeFUT([ @@ -26,7 +25,7 @@ def test_bad_endpoint(self): "http://someendpoint", ]) returncode = cli.run() - ok_(returncode not in (None, 0)) + assert returncode not in (None, 0) @patch("autopush.diagnostic_cli.AutopushConfig") @patch("autopush.diagnostic_cli.DatabaseManager.from_config") diff --git a/autopush/tests/test_endpoint.py b/autopush/tests/test_endpoint.py index dc9b7951..4a8fdb41 100644 --- a/autopush/tests/test_endpoint.py +++ b/autopush/tests/test_endpoint.py @@ -4,7 +4,6 @@ import twisted.internet.base from cryptography.fernet import Fernet, InvalidToken from mock import Mock, patch -from nose.tools import eq_, ok_ from twisted.internet.defer import inlineCallbacks from twisted.trial import unittest @@ -67,27 +66,27 @@ def test_delete_token_invalid(self): self.fernet_mock.configure_mock(**{ "decrypt.side_effect": InvalidToken}) resp = yield self.client.delete(self.url(message_id='%20')) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_delete_token_wrong_components(self): self.fernet_mock.decrypt.return_value = "123:456" resp = yield self.client.delete(self.url(message_id="ignored")) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_delete_token_wrong_kind(self): tok = ":".join(["r", dummy_uaid.hex, str(dummy_chid)]) self.fernet_mock.decrypt.return_value = tok resp = yield self.client.delete(self.url(message_id='ignored')) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_delete_invalid_timestamp_token(self): tok = ":".join(["02", str(dummy_chid)]) self.fernet_mock.decrypt.return_value = tok resp = yield self.client.delete(self.url(message_id='ignored')) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_delete_success(self): @@ -97,7 +96,7 @@ def test_delete_success(self): "delete_message.return_value": True}) resp = yield self.client.delete(self.url(message_id="123-456")) self.message_mock.delete_message.assert_called() - eq_(resp.get_status(), 204) + assert resp.get_status() == 204 @inlineCallbacks def test_delete_topic_success(self): @@ -107,7 +106,7 @@ def test_delete_topic_success(self): "delete_message.return_value": True}) resp = yield self.client.delete(self.url(message_id="123-456")) self.message_mock.delete_message.assert_called() - eq_(resp.get_status(), 204) + assert resp.get_status() == 204 @inlineCallbacks def test_delete_topic_error_parts(self): @@ -116,7 +115,7 @@ def test_delete_topic_error_parts(self): self.message_mock.configure_mock(**{ "delete_message.return_value": True}) resp = yield self.client.delete(self.url(message_id="123-456")) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_delete_db_error(self): @@ -126,7 +125,7 @@ def test_delete_db_error(self): "delete_message.side_effect": ProvisionedThroughputExceededException(None, None)}) resp = yield self.client.delete(self.url(message_id="ignored")) - eq_(resp.get_status(), 503) + assert resp.get_status() == 503 class RegistrationTestCase(unittest.TestCase): @@ -181,40 +180,40 @@ def test_base_tags(self): self.reg.request = Mock(headers={'user-agent': 'test'}, host='example.com:8080') tags = self.reg.base_tags() - eq_(tags, ['user_agent:test', 'host:example.com:8080']) + assert tags == ['user_agent:test', 'host:example.com:8080'] # previously failed tags = self.reg.base_tags() - eq_(tags, ['user_agent:test', 'host:example.com:8080']) + assert tags == ['user_agent:test', 'host:example.com:8080'] def _check_error(self, resp, code, errno, error, message=None): d = json.loads(resp.content) - eq_(d.get("code"), code) - eq_(d.get("errno"), errno) - eq_(d.get("error"), error) + assert d.get("code") == code + assert d.get("errno") == errno + assert d.get("error") == error def test_init_info(self): h = self.request_mock.headers h["user-agent"] = "myself" d = self.reg._init_info() - eq_(d["user_agent"], "myself") + assert d["user_agent"] == "myself" self.request_mock.remote_ip = "local1" d = self.reg._init_info() - eq_(d["remote_ip"], "local1") + assert d["remote_ip"] == "local1" self.request_mock.headers["x-forwarded-for"] = "local2" d = self.reg._init_info() - eq_(d["remote_ip"], "local2") + assert d["remote_ip"] == "local2" def test_conf_crypto_key(self): fake = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' conf = AutopushConfig(crypto_key=fake) - eq_(conf.fernet._fernets[0]._encryption_key, + assert conf.fernet._fernets[0]._encryption_key == ( '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') fake2 = 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=' conf = AutopushConfig(crypto_key=[fake, fake2]) - eq_(conf.fernet._fernets[0]._encryption_key, + assert conf.fernet._fernets[0]._encryption_key == ( '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') - eq_(conf.fernet._fernets[1]._encryption_key, + assert conf.fernet._fernets[1]._encryption_key == ( '\x10A\x04\x10A\x04\x10A\x04\x10A\x04\x10A\x04\x10') def test_cors(self): @@ -222,15 +221,15 @@ def test_cors(self): ch2 = "Access-Control-Allow-Methods" reg = self.reg reg.conf.cors = False - ok_(reg._headers.get(ch1) != "*") - ok_(reg._headers.get(ch2) != self.CORS_HEAD) + assert reg._headers.get(ch1) != "*" + assert reg._headers.get(ch2) != self.CORS_HEAD reg.clear_header(ch1) reg.clear_header(ch2) reg.conf.cors = True reg.prepare() - eq_(reg._headers[ch1], "*") - eq_(reg._headers[ch2], self.CORS_HEAD) + assert reg._headers[ch1] == "*" + assert reg._headers[ch2] == self.CORS_HEAD def test_cors_head(self): ch1 = "Access-Control-Allow-Origin" @@ -239,8 +238,8 @@ def test_cors_head(self): reg.conf.cors = True reg.prepare() reg.head(None) - eq_(reg._headers[ch1], "*") - eq_(reg._headers[ch2], self.CORS_HEAD) + assert reg._headers[ch1] == "*" + assert reg._headers[ch2] == self.CORS_HEAD def test_cors_options(self): ch1 = "Access-Control-Allow-Origin" @@ -249,8 +248,8 @@ def test_cors_options(self): reg.conf.cors = True reg.prepare() reg.options(None) - eq_(reg._headers[ch1], "*") - eq_(reg._headers[ch2], self.CORS_HEAD) + assert reg._headers[ch1] == "*" + assert reg._headers[ch2] == self.CORS_HEAD @inlineCallbacks def test_post(self): @@ -269,13 +268,13 @@ def test_post(self): data={}, )) ) - eq_(resp.get_status(), 200) + assert resp.get_status() == 200 payload = json.loads(resp.content) - eq_(payload["uaid"], dummy_uaid.hex) - eq_(payload["channelID"], dummy_chid.hex) - eq_(payload["endpoint"], "http://localhost/wpush/v1/abcd123") - ok_("secret" in payload) + assert payload["uaid"] == dummy_uaid.hex + assert payload["channelID"] == dummy_chid.hex + assert payload["endpoint"] == "http://localhost/wpush/v1/abcd123" + assert "secret" in payload @inlineCallbacks def test_post_gcm(self): @@ -302,16 +301,16 @@ def test_post_gcm(self): token="182931248179192", )) ) - eq_(resp.get_status(), 200) + assert resp.get_status() == 200 payload = json.loads(resp.content) - eq_(payload["uaid"], dummy_uaid.hex) - eq_(payload["channelID"], dummy_chid.hex) - eq_(payload["endpoint"], "http://localhost/wpush/v1/abcd123") + assert payload["uaid"] == dummy_uaid.hex + assert payload["channelID"] == dummy_chid.hex + assert payload["endpoint"] == "http://localhost/wpush/v1/abcd123" calls = self.db.router.register_user.call_args call_args = calls[0][0] - eq_(True, has_connected_this_month(call_args)) - ok_("secret" in payload) + assert has_connected_this_month(call_args) is True + assert "secret" in payload @inlineCallbacks def test_post_invalid_args(self, *args): @@ -374,8 +373,8 @@ def test_post_existing_uaid(self): )) ) payload = json.loads(resp.content) - eq_(payload["channelID"], dummy_chid.hex) - eq_(payload["endpoint"], "http://localhost/wpush/v1/abcd123") + assert payload["channelID"] == dummy_chid.hex + assert payload["endpoint"] == "http://localhost/wpush/v1/abcd123" @inlineCallbacks def test_no_uaid(self): @@ -434,8 +433,8 @@ def test_post_nochid(self, *args): )) ) payload = json.loads(resp.content) - eq_(payload["channelID"], dummy_chid.hex) - eq_(payload["endpoint"], "http://localhost/wpush/v1/abcd123") + assert payload["channelID"] == dummy_chid.hex + assert payload["endpoint"] == "http://localhost/wpush/v1/abcd123" @inlineCallbacks def test_post_with_app_server_key(self, *args): @@ -444,17 +443,17 @@ def test_post_with_app_server_key(self, *args): dummy_key = "RandomKeyString" def mock_encrypt(cleartext): - eq_(len(cleartext), 64) + assert len(cleartext) == 64 # dummy_uaid - eq_(cleartext[0:16], + assert cleartext[0:16] == ( 'abad1dea00000000aabbccdd00000000'.decode('hex')) # dummy_chid - eq_(cleartext[16:32], + assert cleartext[16:32] == ( 'deadbeef00000000decafbad00000000'.decode('hex')) # sha256(dummy_key).digest() - eq_(cleartext[32:], - ('47aedd050b9e19171f0fa7b8b65ca670' - '28f0bc92cd3f2cd3682b1200ec759007').decode('hex')) + assert cleartext[32:] == ( + '47aedd050b9e19171f0fa7b8b65ca670' + '28f0bc92cd3f2cd3682b1200ec759007').decode('hex') return 'abcd123' self.fernet_mock.configure_mock(**{ 'encrypt.side_effect': mock_encrypt, @@ -471,8 +470,8 @@ def mock_encrypt(cleartext): )) ) payload = json.loads(resp.content) - eq_(payload["channelID"], dummy_chid.hex) - eq_(payload["endpoint"], "http://localhost/wpush/v2/abcd123") + assert payload["channelID"] == dummy_chid.hex + assert payload["endpoint"] == "http://localhost/wpush/v2/abcd123" @inlineCallbacks def test_put(self, *args): @@ -490,16 +489,16 @@ def test_put(self, *args): body=json.dumps(data), ) payload = json.loads(resp.content) - eq_(payload, {}) + assert payload == {} frouter.register.assert_called_with( uaid="", router_data=data, app_id='test', ) user_data = self.db.router.register_user.call_args[0][0] - eq_(user_data['uaid'], dummy_uaid.hex) - eq_(user_data['router_type'], 'test') - eq_(user_data['router_data']['token'], 'some_token') + assert user_data['uaid'] == dummy_uaid.hex + assert user_data['router_type'] == 'test' + assert user_data['router_data']['token'] == 'some_token' @inlineCallbacks def test_put_bad_auth(self, *args): @@ -521,7 +520,7 @@ def test_put_bad_uaid_path(self, *args): headers={"Authorization": "Fred Smith"}, body=json.dumps(dict(token="blah")) ) - eq_(resp.get_status(), 404) + assert resp.get_status() == 404 @inlineCallbacks def test_put_bad_arguments(self, *args): @@ -619,8 +618,9 @@ def test_delete_uaid(self): ) # Note: Router is mocked, so the UAID is never actually # dropped. - ok_(self.db.router.drop_user.called) - eq_(self.db.router.drop_user.call_args_list[0][0], (dummy_uaid.hex,)) + assert self.db.router.drop_user.called + assert self.db.router.drop_user.call_args_list[0][0] == ( + dummy_uaid.hex,) @inlineCallbacks def test_delete_bad_uaid(self): @@ -630,7 +630,7 @@ def test_delete_bad_uaid(self): uaid=uuid.uuid4().hex), headers={"Authorization": self.auth}, ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_delete_orphans(self): @@ -641,7 +641,7 @@ def test_delete_orphans(self): uaid=dummy_uaid.hex), headers={"Authorization": self.auth}, ) - eq_(resp.get_status(), 410) + assert resp.get_status() == 410 @inlineCallbacks def test_delete_bad_auth(self, *args): @@ -651,7 +651,7 @@ def test_delete_bad_auth(self, *args): uaid=dummy_uaid.hex), headers={"Authorization": "Invalid"}, ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_delete_bad_router(self): @@ -661,7 +661,7 @@ def test_delete_bad_router(self): uaid=dummy_uaid.hex), headers={"Authorization": self.auth}, ) - eq_(resp.get_status(), 400) + assert resp.get_status() == 400 @inlineCallbacks def test_get(self): @@ -677,5 +677,5 @@ def test_get(self): ) self.db.message.all_channels.assert_called_with(str(dummy_uaid)) payload = json.loads(resp.content) - eq_(chids, payload['channelIDs']) - eq_(dummy_uaid.hex, payload['uaid']) + assert chids == payload['channelIDs'] + assert dummy_uaid.hex == payload['uaid'] diff --git a/autopush/tests/test_health.py b/autopush/tests/test_health.py index 031fb066..df47605c 100644 --- a/autopush/tests/test_health.py +++ b/autopush/tests/test_health.py @@ -3,7 +3,6 @@ import twisted.internet.base from boto.dynamodb2.exceptions import InternalServerError from mock import Mock -from nose.tools import eq_ from twisted.internet.defer import inlineCallbacks from twisted.logger import globalLogPublisher from twisted.trial import unittest @@ -118,10 +117,10 @@ def raise_error(*args, **kwargs): def _assert_reply(self, reply, exception=None): resp = yield self.client.get('/health') if exception: - eq_(resp.get_status(), 503) + assert resp.get_status() == 503 self.flushLoggedErrors(exception) payload = json.loads(resp.content) - eq_(payload, reply) + assert payload == reply class StatusTestCase(unittest.TestCase): diff --git a/autopush/tests/test_integration.py b/autopush/tests/test_integration.py index 16a228d7..95d02324 100644 --- a/autopush/tests/test_integration.py +++ b/autopush/tests/test_integration.py @@ -21,7 +21,6 @@ import websocket from cryptography.fernet import Fernet from jose import jws -from nose.tools import eq_, ok_ from typing import Optional # noqa from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks, returnValue, Deferred @@ -51,7 +50,7 @@ twisted.internet.base.DelayedCall.debug = True -def setUp(): +def setup_module(): logging.getLogger('boto').setLevel(logging.CRITICAL) if "SKIP_INTEGRATION" in os.environ: # pragma: nocover raise SkipTest("Skipping integration tests") @@ -116,7 +115,7 @@ def hello(self, uaid=None): self.ws.send(msg) result = json.loads(self.ws.recv()) log.debug("Recv: %s", result) - eq_(result["status"], 200) + assert result["status"] == 200 if self.uaid and self.uaid != result["uaid"]: # pragma: nocover log.debug("Mismatch on re-using uaid. Old: %s, New: %s", self.uaid, result["uaid"]) @@ -133,8 +132,8 @@ def register(self, chid=None, key=None): self.ws.send(msg) result = json.loads(self.ws.recv()) log.debug("Recv: %s", result) - eq_(result["status"], 200) - eq_(result["channelID"], chid) + assert result["status"] == 200 + assert result["channelID"] == chid self.channels[chid] = result["pushEndpoint"] return result @@ -162,7 +161,7 @@ def delete_notification(self, channel, message=None, status=204): http.request("DELETE", url.path) resp = http.getresponse() http.close() - eq_(resp.status, status) + assert resp.status == status def send_notification(self, channel=None, version=None, data=None, use_header=True, status=None, ttl=200, @@ -208,17 +207,17 @@ def send_notification(self, channel=None, version=None, data=None, resp = http.getresponse() log.debug("%s Response (%s): %s", method, resp.status, resp.read()) http.close() - eq_(resp.status, status) + assert resp.status == status self.notif_response = resp location = resp.getheader("Location", None) log.debug("Response Headers: %s", resp.getheaders()) if status >= 200 and status < 300: - ok_(location is not None) + assert location is not None if status == 201 and ttl is not None: ttl_header = resp.getheader("TTL") - eq_(ttl_header, str(ttl)) + assert ttl_header == str(ttl) if ttl != 0 and status == 201: - ok_(location is not None) + assert location is not None if channel in self.messages: self.messages[channel].append(location) else: @@ -245,7 +244,7 @@ def ping(self): self.ws.send("{}") result = self.ws.recv() log.debug("Recv: %s", result) - eq_(result, "{}") + assert result == "{}" return result def ack(self, channel, version): @@ -421,22 +420,21 @@ class Test_Data(IntegrationBase): @inlineCallbacks def test_webpush_data_delivery_to_connected_client(self): client = yield self.quick_register() - ok_(client.channels) + assert client.channels chan = client.channels.keys()[0] # Invalid UTF-8 byte sequence. data = b"\xc3\x28\xa0\xa1\xe2\x28\xa1" result = yield client.send_notification(data=data) - ok_(result is not None) - eq_(result["messageType"], "notification") - eq_(result["channelID"], chan) - eq_(result["data"], "wyigoeIooQ") - ok_(self.logs.logged_ci(lambda ci: 'message_size' in ci), - "message_size not logged") - ok_(self.logs.logged_ci( + assert result is not None + assert result["messageType"] == "notification" + assert result["channelID"] == chan + assert result["data"] == "wyigoeIooQ" + assert self.logs.logged_ci(lambda ci: 'message_size' in ci) + assert self.logs.logged_ci( lambda ci: ci['encoding'] == "aesgcm" - )) + ) yield self.shut_down(client) @inlineCallbacks @@ -444,22 +442,21 @@ def test_webpush_data_delivery_to_connected_client_uaid_fail(self): from boto.dynamodb2.exceptions import ItemNotFound client = yield self.quick_register() self.conn.db.router.get_uaid = Mock(side_effect=ItemNotFound) - ok_(client.channels) + assert client.channels chan = client.channels.keys()[0] # Invalid UTF-8 byte sequence. data = b"\xc3\x28\xa0\xa1\xe2\x28\xa1" result = yield client.send_notification(data=data) - ok_(result is not None) - eq_(result["messageType"], "notification") - eq_(result["channelID"], chan) - eq_(result["data"], "wyigoeIooQ") - ok_(self.logs.logged_ci(lambda ci: 'message_size' in ci), - "message_size not logged") - ok_(self.logs.logged_ci( + assert result is not None + assert result["messageType"] == "notification" + assert result["channelID"] == chan + assert result["data"] == "wyigoeIooQ" + assert self.logs.logged_ci(lambda ci: 'message_size' in ci) + assert self.logs.logged_ci( lambda ci: ci['encoding'] == "aesgcm" - )) + ) yield self.shut_down(client) @inlineCallbacks @@ -512,20 +509,19 @@ def test_webpush_data_delivery_to_disconnected_client(self, m_ddog): for chan in tests: result = yield client.get_notification() - ok_(result is not None) + assert result is not None chan = result["channelID"] test = tests[chan] - eq_(result["data"], test["result"]) + assert result["data"] == test["result"] headers = result["headers"] - ok_("crypto_key" in headers) - ok_("encryption" in headers) - ok_("encoding" in headers) + assert "crypto_key" in headers + assert "encryption" in headers + assert "encoding" in headers yield client.ack(chan, result["version"]) - ok_(self.logs.logged_ci(lambda ci: 'message_size' in ci), - "message_size not logged") + assert self.logs.logged_ci(lambda ci: 'message_size' in ci) inc_call = self.conn.db.metrics._client.increment.call_args_list[5] - eq_(inc_call[1]['tags'], ['source:Stored']) + assert inc_call[1]['tags'] == ['source:Stored'] yield self.shut_down(client) @inlineCallbacks @@ -551,7 +547,7 @@ class TestLoop(IntegrationBase): def test_basic_deliver(self): client = yield self.quick_register() result = yield client.send_notification() - ok_(result != {}) + assert result != {} yield self.shut_down(client) @inlineCallbacks @@ -568,8 +564,8 @@ def test_uaid_resumption_on_reconnect(self): yield client.connect() yield client.hello() result = yield client.send_notification() - ok_(result != {}) - eq_(result["channelID"], chan) + assert result != {} + assert result["channelID"] == chan yield self.shut_down(client) @@ -585,11 +581,11 @@ def test_hello_only_has_three_calls(self): client = Client(self._ws_url) yield client.connect() result = yield client.hello() - ok_(result != {}) - eq_(result["use_webpush"], True) + assert result != {} + assert result["use_webpush"] is True yield client.wait_for(lambda: len(db.DB_CALLS) == 3) - eq_(db.DB_CALLS, ['register_user', 'fetch_messages', - 'fetch_timestamp_messages']) + assert db.DB_CALLS == ['register_user', 'fetch_messages', + 'fetch_timestamp_messages'] db.DB_CALLS = [] db.TRACK_DB_CALLS = False @@ -600,8 +596,8 @@ def test_hello_echo(self): client = Client(self._ws_url) yield client.connect() result = yield client.hello() - ok_(result != {}) - eq_(result["use_webpush"], True) + assert result != {} + assert result["use_webpush"] is True yield self.shut_down(client) @inlineCallbacks @@ -610,9 +606,9 @@ def test_hello_with_bad_prior_uaid(self): client = Client(self._ws_url) yield client.connect() result = yield client.hello(uaid=non_uaid) - ok_(result != {}) - ok_(result["uaid"] != non_uaid) - eq_(result["use_webpush"], True) + assert result != {} + assert result["uaid"] != non_uaid + assert result["use_webpush"] is True yield self.shut_down(client) @inlineCallbacks @@ -620,22 +616,22 @@ def test_basic_delivery(self): data = str(uuid.uuid4()) client = yield self.quick_register() result = yield client.send_notification(data=data) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield self.shut_down(client) log_event = self.logs.logged_session() - eq_(log_event["connection_type"], "webpush") - eq_(log_event["direct_storage"], 1) + assert log_event["connection_type"] == "webpush" + assert log_event["direct_storage"] == 1 @inlineCallbacks def test_topic_basic_delivery(self): data = str(uuid.uuid4()) client = yield self.quick_register() result = yield client.send_notification(data=data, topic="Inbox") - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield self.shut_down(client) @inlineCallbacks @@ -649,11 +645,11 @@ def test_topic_replacement_delivery(self): yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data2)) - eq_(result["messageType"], "notification") + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data2) + assert result["messageType"] == "notification" result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -665,15 +661,15 @@ def test_topic_no_delivery_on_reconnect(self): yield client.connect() yield client.hello() result = yield client.get_notification(timeout=10) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield client.ack(result["channelID"], result["version"]) yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield client.disconnect() yield client.connect() yield client.hello() @@ -685,11 +681,10 @@ def test_basic_delivery_with_vapid(self): client = yield self.quick_register() vapid_info = _get_vapid() result = yield client.send_notification(data=data, vapid=vapid_info) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") - ok_(self.logs.logged_ci(lambda ci: 'router_key' in ci), - "router_key not logged") + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" + assert self.logs.logged_ci(lambda ci: 'router_key' in ci) yield self.shut_down(client) @inlineCallbacks @@ -762,20 +757,20 @@ def test_delivery_repeat_without_ack(self): data = str(uuid.uuid4()) client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels yield client.send_notification(data=data) yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - eq_(result["data"], base64url_encode(data)) + assert result != {} + assert result["data"] == base64url_encode(data) yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - eq_(result["data"], base64url_encode(data)) + assert result != {} + assert result["data"] == base64url_encode(data) yield self.shut_down(client) @inlineCallbacks @@ -784,27 +779,27 @@ def test_multiple_delivery_repeat_without_ack(self): data2 = str(uuid.uuid4()) client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels yield client.send_notification(data=data) yield client.send_notification(data=data2) yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) yield self.shut_down(client) @inlineCallbacks @@ -813,29 +808,29 @@ def test_multiple_legacy_delivery_with_single_ack(self): data2 = str(uuid.uuid4()) client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels with self.legacy_endpoint(): yield client.send_notification(data=data) yield client.send_notification(data=data2) yield client.connect() yield client.hello() result = yield client.get_notification(timeout=5) - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) yield client.ack(result["channelID"], result["version"]) yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) - ok_(result["messageType"], "notification") + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) + assert result["messageType"] == "notification" result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -844,29 +839,29 @@ def test_multiple_delivery_with_single_ack(self): data2 = str(uuid.uuid4()) client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels yield client.send_notification(data=data) yield client.send_notification(data=data2) yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - eq_(result["data"], base64url_encode(data)) + assert result != {} + assert result["data"] == base64url_encode(data) result2 = yield client.get_notification() - ok_(result2 != {}) - eq_(result2["data"], base64url_encode(data2)) + assert result2 != {} + assert result2["data"] == base64url_encode(data2) yield client.ack(result["channelID"], result["version"]) yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - eq_(result["data"], base64url_encode(data)) - ok_(result["messageType"], "notification") + assert result != {} + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" result2 = yield client.get_notification() - ok_(result2 != {}) - eq_(result2["data"], base64url_encode(data2)) + assert result2 != {} + assert result2["data"] == base64url_encode(data2) yield client.ack(result2["channelID"], result2["version"]) # Verify no messages are delivered @@ -874,7 +869,7 @@ def test_multiple_delivery_with_single_ack(self): yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result is None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -883,17 +878,17 @@ def test_multiple_delivery_with_multiple_ack(self): data2 = str(uuid.uuid4()) client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels yield client.send_notification(data=data) yield client.send_notification(data=data2) yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result != {}) - ok_(result["data"] in map(base64url_encode, [data, data2])) + assert result != {} + assert result["data"] in map(base64url_encode, [data, data2]) result2 = yield client.get_notification() - ok_(result2 != {}) - ok_(result2["data"] in map(base64url_encode, [data, data2])) + assert result2 != {} + assert result2["data"] in map(base64url_encode, [data, data2]) yield client.ack(result2["channelID"], result2["version"]) yield client.ack(result["channelID"], result["version"]) @@ -901,28 +896,29 @@ def test_multiple_delivery_with_multiple_ack(self): yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks def test_no_delivery_to_unregistered(self): data = str(uuid.uuid4()) client = yield self.quick_register() # type: Client - ok_(client.channels) + assert client.channels chan = client.channels.keys()[0] result = yield client.send_notification(data=data) - eq_(result["channelID"], chan) - eq_(result["data"], base64url_encode(data)) + assert result["channelID"] == chan + assert result["data"] == base64url_encode(data) yield client.ack(result["channelID"], result["version"]) yield client.unregister(chan) result = yield client.send_notification(data=data, status=410) # Verify cache-control - eq_(client.notif_response.getheader("Cache-Control"), "max-age=86400") + assert client.notif_response.getheader("Cache-Control") == \ + "max-age=86400" - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -935,7 +931,7 @@ def test_ttl_not_present_not_connected(self): yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -943,10 +939,10 @@ def test_ttl_not_present_connected(self): data = str(uuid.uuid4()) client = yield self.quick_register() result = yield client.send_notification(data=data, ttl=None) - ok_(result is not None) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result is not None + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield self.shut_down(client) @inlineCallbacks @@ -954,15 +950,15 @@ def test_ttl_not_present_connected_no_ack(self): data = str(uuid.uuid4()) client = yield self.quick_register() result = yield client.send_notification(data=data, ttl=None) - ok_(result is not None) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result is not None + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield client.disconnect() yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -970,10 +966,10 @@ def test_ttl_0_connected(self): data = str(uuid.uuid4()) client = yield self.quick_register() result = yield client.send_notification(data=data, ttl=0) - ok_(result is not None) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data)) - eq_(result["messageType"], "notification") + assert result is not None + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data) + assert result["messageType"] == "notification" yield self.shut_down(client) @inlineCallbacks @@ -985,7 +981,7 @@ def test_ttl_0_not_connected(self): yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -998,7 +994,7 @@ def test_ttl_expired(self): yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -1015,12 +1011,12 @@ def test_ttl_batch_expired_and_good_one(self): yield client.connect() yield client.hello() result = yield client.get_notification(timeout=4) - ok_(result is not None) - eq_(result["headers"]["encryption"], client._crypto_key) - eq_(result["data"], base64url_encode(data2)) - eq_(result["messageType"], "notification") + assert result is not None + assert result["headers"]["encryption"] == client._crypto_key + assert result["data"] == base64url_encode(data2) + assert result["messageType"] == "notification" result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -1044,19 +1040,19 @@ def test_ttl_batch_partly_expired_and_good_one(self): # Pull out and ack the first for x in range(0, 6): result = yield client.get_notification(timeout=4) - ok_(result is not None) - eq_(result["data"], base64url_encode(data)) + assert result is not None + assert result["data"] == base64url_encode(data) yield client.ack(result["channelID"], result["version"]) # Should have one more that is data2, this will only arrive if the # other six were acked as that hits the batch size result = yield client.get_notification(timeout=4) - ok_(result is not None) - eq_(result["data"], base64url_encode(data2)) + assert result is not None + assert result["data"] == base64url_encode(data2) # No more result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -1065,7 +1061,7 @@ def test_message_without_crypto_headers(self): client = yield self.quick_register() result = yield client.send_notification(data=data, use_header=False, status=400) - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -1085,10 +1081,10 @@ def test_message_with_topic(self): def test_empty_message_without_crypto_headers(self): client = yield self.quick_register() result = yield client.send_notification(use_header=False) - ok_(result is not None) - eq_(result["messageType"], "notification") - ok_("headers" not in result) - ok_("data" not in result) + assert result is not None + assert result["messageType"] == "notification" + assert "headers" not in result + assert "data" not in result yield client.ack(result["channelID"], result["version"]) yield client.disconnect() @@ -1096,9 +1092,9 @@ def test_empty_message_without_crypto_headers(self): yield client.connect() yield client.hello() result = yield client.get_notification() - ok_(result is not None) - ok_("headers" not in result) - ok_("data" not in result) + assert result is not None + assert "headers" not in result + assert "data" not in result yield client.ack(result["channelID"], result["version"]) yield self.shut_down(client) @@ -1107,17 +1103,17 @@ def test_empty_message_without_crypto_headers(self): def test_empty_message_with_crypto_headers(self): client = yield self.quick_register() result = yield client.send_notification() - ok_(result is not None) - eq_(result["messageType"], "notification") - ok_("headers" not in result) - ok_("data" not in result) + assert result is not None + assert result["messageType"] == "notification" + assert "headers" not in result + assert "data" not in result result2 = yield client.send_notification() # We shouldn't store headers for blank messages. - ok_(result2 is not None) - eq_(result2["messageType"], "notification") - ok_("headers" not in result2) - ok_("data" not in result2) + assert result2 is not None + assert result2["messageType"] == "notification" + assert "headers" not in result2 + assert "data" not in result2 yield client.ack(result["channelID"], result["version"]) yield client.ack(result2["channelID"], result2["version"]) @@ -1127,9 +1123,9 @@ def test_empty_message_with_crypto_headers(self): yield client.connect() yield client.hello() result3 = yield client.get_notification() - ok_(result3 is not None) - ok_("headers" not in result3) - ok_("data" not in result3) + assert result3 is not None + assert "headers" not in result3 + assert "data" not in result3 yield client.ack(result3["channelID"], result3["version"]) yield self.shut_down(client) @@ -1138,14 +1134,14 @@ def test_empty_message_with_crypto_headers(self): def test_delete_saved_notification(self): client = yield self.quick_register() yield client.disconnect() - ok_(client.channels) + assert client.channels chan = client.channels.keys()[0] yield client.send_notification() yield client.delete_notification(chan) yield client.connect() yield client.hello() result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @inlineCallbacks @@ -1166,22 +1162,22 @@ def test_webpush_monthly_rotation(self): # Verify the move c = yield deferToThread(self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], last_month) + assert c["current_month"] == last_month # Verify last_connect is current, then move that back - ok_(has_connected_this_month(c)) + assert has_connected_this_month(c) today = get_month(delta=-1) - c["last_connect"] = "%s%s020001" % (today.year, - str(today.month).zfill(2)) + c["last_connect"] = int("%s%s020001" % (today.year, + str(today.month).zfill(2))) yield deferToThread(c.partial_save) - eq_(False, has_connected_this_month(c)) + assert has_connected_this_month(c) is False # Move the clients channels back one month exists, chans = yield deferToThread( self.conn.db.message.all_channels, client.uaid ) - eq_(exists, True) - eq_(len(chans), 1) + assert exists is True + assert len(chans) == 1 yield deferToThread( lm_message.save_channels, client.uaid, @@ -1200,8 +1196,8 @@ def test_webpush_monthly_rotation(self): self.conn.db.message.all_channels, client.uaid ) - eq_(exists, False) - eq_(len(chans), 0) + assert exists is False + assert len(chans) == 0 # Send in a notification, verify it landed in last months notification # table @@ -1211,7 +1207,7 @@ def test_webpush_monthly_rotation(self): ts, notifs = yield deferToThread(lm_message.fetch_timestamp_messages, uuid.UUID(client.uaid), " ") - eq_(len(notifs), 1) + assert len(notifs) == 1 # Connect the client, verify the migration yield client.connect() @@ -1220,12 +1216,12 @@ def test_webpush_monthly_rotation(self): # Pull down the notification result = yield client.get_notification() chan = client.channels.keys()[0] - ok_(result is not None) - eq_(chan, result["channelID"]) + assert result is not None + assert chan == result["channelID"] # Check that the client is going to rotate the month server_client = self.conn.clients[client.uaid] - eq_(server_client.ps.rotate_message_table, True) + assert server_client.ps.rotate_message_table is True # Acknowledge the notification, which triggers the migration yield client.ack(chan, result["version"]) @@ -1243,19 +1239,19 @@ def test_webpush_monthly_rotation(self): # Verify the month update in the router table c = yield deferToThread( self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], self.conn.db.current_msg_month) - eq_(server_client.ps.rotate_message_table, False) + assert c["current_month"] == self.conn.db.current_msg_month + assert server_client.ps.rotate_message_table is False # Verify the client moved last_connect - eq_(True, has_connected_this_month(c)) + assert has_connected_this_month(c) is True # Verify the channels were moved exists, chans = yield deferToThread( self.conn.db.message.all_channels, client.uaid ) - eq_(exists, True) - eq_(len(chans), 1) + assert exists is True + assert len(chans) == 1 yield self.shut_down(client) @@ -1277,22 +1273,22 @@ def test_webpush_monthly_rotation_prior_record_exists(self): # Verify the move c = yield deferToThread(self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], last_month) + assert c["current_month"] == last_month # Verify last_connect is current, then move that back - ok_(has_connected_this_month(c)) + assert has_connected_this_month(c) today = get_month(delta=-1) - c["last_connect"] = "%s%s020001" % (today.year, - str(today.month).zfill(2)) + c["last_connect"] = int("%s%s020001" % (today.year, + str(today.month).zfill(2))) yield deferToThread(c.partial_save) - eq_(False, has_connected_this_month(c)) + assert has_connected_this_month(c) is False # Move the clients channels back one month exists, chans = yield deferToThread( self.conn.db.message.all_channels, client.uaid ) - eq_(exists, True) - eq_(len(chans), 1) + assert exists is True + assert len(chans) == 1 yield deferToThread( lm_message.save_channels, client.uaid, @@ -1307,7 +1303,7 @@ def test_webpush_monthly_rotation_prior_record_exists(self): _, notifs = yield deferToThread(lm_message.fetch_timestamp_messages, uuid.UUID(client.uaid), " ") - eq_(len(notifs), 1) + assert len(notifs) == 1 # Connect the client, verify the migration yield client.connect() @@ -1316,12 +1312,12 @@ def test_webpush_monthly_rotation_prior_record_exists(self): # Pull down the notification result = yield client.get_notification() chan = client.channels.keys()[0] - ok_(result is not None) - eq_(chan, result["channelID"]) + assert result is not None + assert chan == result["channelID"] # Check that the client is going to rotate the month server_client = self.conn.clients[client.uaid] - eq_(server_client.ps.rotate_message_table, True) + assert server_client.ps.rotate_message_table is True # Acknowledge the notification, which triggers the migration yield client.ack(chan, result["version"]) @@ -1338,19 +1334,19 @@ def test_webpush_monthly_rotation_prior_record_exists(self): # Verify the month update in the router table c = yield deferToThread(self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], self.conn.db.current_msg_month) - eq_(server_client.ps.rotate_message_table, False) + assert c["current_month"] == self.conn.db.current_msg_month + assert server_client.ps.rotate_message_table is False # Verify the client moved last_connect - eq_(True, has_connected_this_month(c)) + assert has_connected_this_month(c) is True # Verify the channels were moved exists, chans = yield deferToThread( self.conn.db.message.all_channels, client.uaid ) - eq_(exists, True) - eq_(len(chans), 1) + assert exists is True + assert len(chans) == 1 yield self.shut_down(client) @@ -1373,15 +1369,15 @@ def test_webpush_monthly_rotation_no_channels(self): # Verify the move c = yield deferToThread(self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], last_month) + assert c["current_month"] == last_month # Verify there's no channels exists, chans = yield deferToThread( self.conn.db.message.all_channels, client.uaid ) - eq_(exists, False) - eq_(len(chans), 0) + assert exists is False + assert len(chans) == 0 # Connect the client, verify the migration yield client.connect() @@ -1389,7 +1385,7 @@ def test_webpush_monthly_rotation_no_channels(self): # Check that the client is going to rotate the month server_client = self.conn.clients[client.uaid] - eq_(server_client.ps.rotate_message_table, True) + assert server_client.ps.rotate_message_table is True # Wait up to 2 seconds for the table rotation to occur start = time.time() @@ -1403,8 +1399,8 @@ def test_webpush_monthly_rotation_no_channels(self): # Verify the month update in the router table c = yield deferToThread(self.conn.db.router.get_uaid, client.uaid) - eq_(c["current_month"], self.conn.db.current_msg_month) - eq_(server_client.ps.rotate_message_table, False) + assert c["current_month"] == self.conn.db.current_msg_month + assert server_client.ps.rotate_message_table is False yield self.shut_down(client) @@ -1458,13 +1454,13 @@ def test_client_cert_webpush(self): client = yield self.quick_register( sslcontext=self._create_context(self.auth_client)) yield client.disconnect() - ok_(client.channels) + assert client.channels chan = client.channels.keys()[0] yield client.send_notification() yield client.delete_notification(chan) result = yield client.get_notification() - eq_(result, None) + assert result is None yield self.shut_down(client) @@ -1482,19 +1478,19 @@ def _test_unauth(self, certfile): sslcontext=self._create_context(certfile)) yield client.disconnect() yield client.send_notification(status=401) - ok_(self.logs.logged( + assert self.logs.logged( lambda e: (e['log_format'] == "Failed TLS auth" and (not certfile or - e['client_info']['tls_failed_cn'] == 'localhost')) - )) + e['client_info']['tls_failed_cn'] == 'localhost') + )) response, body = yield _agent( 'DELETE', "https://localhost:9020/m/foo", contextFactory=self.client_SSLCF(certfile)) - eq_(response.code, 401) + assert response.code == 401 wwwauth = response.headers.getRawHeaders('www-authenticate') - eq_(wwwauth, ['Transport mode="tls-client-certificate"']) + assert wwwauth == ['Transport mode="tls-client-certificate"'] @inlineCallbacks def test_log_check_skips_auth(self): @@ -1510,9 +1506,9 @@ def _test_log_check_skips_auth(self, certfile): 'GET', "https://localhost:9020/v1/err", contextFactory=self.client_SSLCF(certfile)) - eq_(response.code, 418) + assert response.code == 418 payload = json.loads(body) - eq_(payload['error'], "Test Error") + assert payload['error'] == "Test Error" @inlineCallbacks def test_status_skips_auth(self): @@ -1528,9 +1524,9 @@ def _test_status_skips_auth(self, certfile): 'GET', "https://localhost:9020/status", contextFactory=self.client_SSLCF(certfile)) - eq_(response.code, 200) + assert response.code == 200 payload = json.loads(body) - eq_(payload, dict(status="OK", version=__version__)) + assert payload == dict(status="OK", version=__version__) @inlineCallbacks def test_health_skips_auth(self): @@ -1546,18 +1542,18 @@ def _test_health_skips_auth(self, certfile): 'GET', "https://localhost:9020/health", contextFactory=self.client_SSLCF(certfile)) - eq_(response.code, 200) + assert response.code == 200 payload = json.loads(body) - eq_(payload['version'], __version__) + assert payload['version'] == __version__ class TestHealth(IntegrationBase): @inlineCallbacks def test_status(self): response, body = yield _agent('GET', "http://localhost:9010/status") - eq_(response.code, 200) + assert response.code == 200 payload = json.loads(body) - eq_(payload, dict(status="OK", version=__version__)) + assert payload == dict(status="OK", version=__version__) class TestGCMBridgeIntegration(IntegrationBase): @@ -1615,7 +1611,7 @@ def test_registration(self): "token": uuid.uuid4().hex, } )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1640,14 +1636,14 @@ def test_registration(self): ) ca_data = self._mock_send.call_args[0][0].data - eq_(response.code, 201) + assert response.code == 201 # ChannelID here MUST match what we got from the registration call. # Currently, this is a lowercase, hex UUID without dashes. - eq_(ca_data['chid'], jbody['channelID']) - eq_(ca_data['con'], content_encoding) - eq_(ca_data['cryptokey'], crypto_key) - eq_(ca_data['enc'], salt) - eq_(ca_data['body'], base64url_encode(data)) + assert ca_data['chid'] == jbody['channelID'] + assert ca_data['con'] == content_encoding + assert ca_data['cryptokey'] == crypto_key + assert ca_data['enc'] == salt + assert ca_data['body'] == base64url_encode(data) @inlineCallbacks def test_invalid_registration(self): @@ -1663,7 +1659,7 @@ def test_invalid_registration(self): "token": uuid.uuid4().hex, } )) - eq_(response.code, 400) + assert response.code == 400 @inlineCallbacks def test_registration_aes128gcm(self): @@ -1679,7 +1675,7 @@ def test_registration_aes128gcm(self): "token": uuid.uuid4().hex, } )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1699,13 +1695,13 @@ def test_registration_aes128gcm(self): ) ca_data = self._mock_send.call_args[0][0].data - eq_(response.code, 201) + assert response.code == 201 # ChannelID here MUST match what we got from the registration call. # Currently, this is a lowercase, hex UUID without dashes. - eq_(ca_data['chid'], jbody['channelID']) - eq_(ca_data['con'], content_encoding) - eq_(ca_data['body'], base64url_encode(data)) - ok_('enc' not in ca_data) + assert ca_data['chid'] == jbody['channelID'] + assert ca_data['con'] == content_encoding + assert ca_data['body'] == base64url_encode(data) + assert 'enc' not in ca_data @inlineCallbacks def test_registration_aes128gcm_bad_(self): @@ -1721,7 +1717,7 @@ def test_registration_aes128gcm_bad_(self): "token": uuid.uuid4().hex, } )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1744,8 +1740,8 @@ def test_registration_aes128gcm_bad_(self): body=data ) - eq_(response.code, 400) - ok_("do not include 'dh' in " in body.lower()) + assert response.code == 400 + assert "do not include 'dh' in " in body.lower() response, body = yield _agent( 'POST', str(jbody['endpoint']), @@ -1756,8 +1752,8 @@ def test_registration_aes128gcm_bad_(self): }), body=data ) - eq_(response.code, 400) - ok_("do not include 'salt' in " in body.lower()) + assert response.code == 400 + assert "do not include 'salt' in " in body.lower() @inlineCallbacks def test_registration_no_token(self): @@ -1772,9 +1768,9 @@ def test_registration_no_token(self): { "chid": str(uuid.uuid4()), "token": '', - } + } )) - eq_(response.code, 400) + assert response.code == 400 class TestFCMBridgeIntegration(IntegrationBase): @@ -1823,7 +1819,7 @@ def test_registration(self): "token": uuid.uuid4().hex, } )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1849,14 +1845,14 @@ def test_registration(self): ca = json.loads(self._mock_send.call_args[0][0][0]) ca_data = ca['data'] - eq_(response.code, 201) + assert response.code == 201 # ChannelID here MUST match what we got from the registration call. # Currently, this is a lowercase, hex UUID without dashes. - eq_(ca_data['chid'], jbody['channelID']) - eq_(ca_data['con'], content_encoding) - eq_(ca_data['cryptokey'], crypto_key) - eq_(ca_data['enc'], salt) - eq_(ca_data['body'], base64url_encode(data)) + assert ca_data['chid'] == jbody['channelID'] + assert ca_data['con'] == content_encoding + assert ca_data['cryptokey'] == crypto_key + assert ca_data['enc'] == salt + assert ca_data['body'] == base64url_encode(data) class TestAPNSBridgeIntegration(IntegrationBase): @@ -1901,7 +1897,7 @@ def test_registration(self): response, body = yield _agent('POST', url, body=json.dumps( {"token": uuid.uuid4().hex} )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1927,17 +1923,17 @@ def test_registration(self): ca_data = json.loads( self._mock_connection.request.call_args[1]['body']) - eq_(response.code, 201) + assert response.code == 201 # ChannelID here MUST match what we got from the registration call. # Currently, this is a lowercase, hex UUID without dashes. - eq_(ca_data['chid'], jbody['channelID']) - eq_(ca_data['con'], content_encoding) - eq_(ca_data['cryptokey'], crypto_key) - eq_(ca_data['enc'], salt) - ok_('mutable-content' in ca_data['aps']) - eq_(ca_data['aps']['alert']['title'], " ") - eq_(ca_data['aps']['alert']['body'], " ") - eq_(ca_data['body'], base64url_encode(data)) + assert ca_data['chid'] == jbody['channelID'] + assert ca_data['con'] == content_encoding + assert ca_data['cryptokey'] == crypto_key + assert ca_data['enc'] == salt + assert 'mutable-content' in ca_data['aps'] + assert ca_data['aps']['alert']['title'] == " " + assert ca_data['aps']['alert']['body'] == " " + assert ca_data['body'] == base64url_encode(data) @inlineCallbacks def test_registration_no_token(self): @@ -1951,7 +1947,7 @@ def test_registration_no_token(self): response, body = yield _agent('POST', url, body=json.dumps( {"token": ''} )) - eq_(response.code, 400) + assert response.code == 400 @inlineCallbacks def test_registration_aps_override(self): @@ -1967,7 +1963,7 @@ def test_registration_aps_override(self): "aps": {"foo": "bar", "gorp": "baz"} } )) - eq_(response.code, 200) + assert response.code == 200 jbody = json.loads(body) # Send a fake message @@ -1993,16 +1989,16 @@ def test_registration_aps_override(self): ca_data = json.loads( self._mock_connection.request.call_args[1]['body']) - eq_(response.code, 201) + assert response.code == 201 # ChannelID here MUST match what we got from the registration call. # Currently, this is a lowercase, hex UUID without dashes. - eq_(ca_data['chid'], jbody['channelID']) - eq_(ca_data['con'], content_encoding) - eq_(ca_data['cryptokey'], crypto_key) - eq_(ca_data['enc'], salt) - ok_('mutable-content' not in ca_data['aps']) - eq_(ca_data['aps']['foo'], "bar") - eq_(ca_data['body'], base64url_encode(data)) + assert ca_data['chid'] == jbody['channelID'] + assert ca_data['con'] == content_encoding + assert ca_data['cryptokey'] == crypto_key + assert ca_data['enc'] == salt + assert 'mutable-content' not in ca_data['aps'] + assert ca_data['aps']['foo'] == "bar" + assert ca_data['body'] == base64url_encode(data) class TestProxyProtocol(IntegrationBase): @@ -2024,10 +2020,10 @@ def test_proxy_protocol(self): '{}GET'.format(proto_line), "http://localhost:{}/v1/err".format(port), ) - eq_(response.code, 418) + assert response.code == 418 payload = json.loads(body) - eq_(payload['error'], "Test Error") - ok_(self.logs.logged_ci(lambda ci: ci.get('remote_ip') == ip)) + assert payload['error'] == "Test Error" + assert self.logs.logged_ci(lambda ci: ci.get('remote_ip') == ip) @inlineCallbacks def test_no_proxy_protocol(self): @@ -2035,9 +2031,9 @@ def test_no_proxy_protocol(self): 'GET', "http://localhost:{}/v1/err".format(self.ep.conf.port), ) - eq_(response.code, 418) + assert response.code == 418 payload = json.loads(body) - eq_(payload['error'], "Test Error") + assert payload['error'] == "Test Error" class TestProxyProtocolSSL(SSLEndpointMixin, IntegrationBase): @@ -2080,10 +2076,10 @@ def wrap_socket(self, sock, *args, **kwargs): http.close() response, body = yield deferToThread(proxy_request) - eq_(response.status, 418) + assert response.status == 418 payload = json.loads(body) - eq_(payload['error'], "Test Error") - ok_(self.logs.logged_ci(lambda ci: ci.get('remote_ip') == ip)) + assert payload['error'] == "Test Error" + assert self.logs.logged_ci(lambda ci: ci.get('remote_ip') == ip) class TestMemUsage(IntegrationBase): @@ -2101,15 +2097,15 @@ def test_memusage(self): 'GET', "http://localhost:{}/_memusage".format(port), ) - eq_(response.code, 200) - ok_('rusage' in body) - ok_('Logger' in body) + assert response.code == 200 + assert 'rusage' in body + assert 'Logger' in body if find_executable('pmap'): - ok_('RSS' in body or 'Rss' in body) # pmap -x or -XX/X output + assert 'RSS' in body or 'Rss' in body # pmap -x or -XX/X output if hasattr(sys, 'pypy_version_info'): # pragma: nocover - ok_('size: ' in body) - ok_('rpy_unicode' in body) - ok_('get_stats_asmmemmgr: (' in body) + assert 'size: ' in body + assert 'rpy_unicode' in body + assert 'get_stats_asmmemmgr: (' in body @inlineCallbacks diff --git a/autopush/tests/test_log_check.py b/autopush/tests/test_log_check.py index acfa5c67..1fdad108 100644 --- a/autopush/tests/test_log_check.py +++ b/autopush/tests/test_log_check.py @@ -1,7 +1,6 @@ import json import twisted -from nose.tools import eq_, ok_ from twisted.internet.defer import inlineCallbacks from twisted.logger import globalLogPublisher from twisted.trial import unittest @@ -34,28 +33,28 @@ def setUp(self): @inlineCallbacks def test_get_err(self): resp = yield self.client.get('/v1/err') - eq_(len(self.logs), 2) - ok_(self.logs.logged( + assert len(self.logs) == 2 + assert self.logs.logged( lambda e: (e['log_level'].name == 'error' and e['log_format'] == 'Test Error Message' and e['status_code'] == 418) - )) + ) payload = json.loads(resp.content) - eq_(payload.get('code'), 418) - eq_(payload.get('message'), "ERROR:Success") + assert payload.get('code') == 418 + assert payload.get('message') == "ERROR:Success" @inlineCallbacks def test_get_crit(self): resp = yield self.client.get('/v1/err/crit') - eq_(len(self.logs), 2) - ok_(self.logs.logged( + assert len(self.logs) == 2 + assert self.logs.logged( lambda e: (e['log_level'].name == 'critical' and e['log_failure'] and e['log_format'] == 'Test Critical Message' and e['status_code'] == 418) - )) + ) payload = json.loads(resp.content) - eq_(payload.get('code'), 418) - eq_(payload.get('error'), "Test Failure") + assert payload.get('code') == 418 + assert payload.get('error') == "Test Failure" self.flushLoggedErrors() diff --git a/autopush/tests/test_logging.py b/autopush/tests/test_logging.py index 7db8a22e..b12a775f 100644 --- a/autopush/tests/test_logging.py +++ b/autopush/tests/test_logging.py @@ -9,7 +9,6 @@ import twisted.trial.unittest from mock import Mock, patch -from nose.tools import eq_, ok_ from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.logger import Logger @@ -65,18 +64,18 @@ def check(): if not logged: # pragma: nocover reactor.callLater(0, check) return - eq_(len(logged), 1) + assert len(logged) == 1 # Check that the sentry data has the client info as a sub dict # Note: these are double quoted, single quote strings. - eq_(logged[0].get('extra').get('client_info'), - {u"'key'": u"'value'"}) + assert logged[0].get('extra').get('client_info') == { + u"'key'": u"'value'"} # Check that the json written actually contains the client info # collapsed up into 'Fields'. out.seek(0) payload = json.loads(out.readline()) - eq_(payload['Fields']['key'], 'value') - eq_(payload['Fields']['key2'], 'value') - eq_(payload['Fields']['key3'], True) + assert payload['Fields']['key'] == 'value' + assert payload['Fields']['key2'] == 'value' + assert payload['Fields']['key3'] is True self._port.stopListening() pl.stop() d.callback(True) @@ -99,12 +98,12 @@ def check(): reactor.callLater(0, check) return - eq_(len(logged), 1) + assert len(logged) == 1 # Ensure a top level stacktrace was included stacktrace = logged[0]['stacktrace'] - ok_(any( + assert any( filename == f['abs_path'] and testname == f['function'] - for f in stacktrace['frames'])) + for f in stacktrace['frames']) self._port.stopListening() pl.stop() @@ -118,19 +117,19 @@ def test_custom_type(self): obj = PushLogger.setup_logging("Autopush") obj._output = mock_stdout = Mock() log.info("omg!", Type=7) - eq_(len(mock_stdout.mock_calls), 2) + assert len(mock_stdout.mock_calls) == 2 kwargs = mock_stdout.mock_calls[0][1][0] - ok_("Type" in kwargs) + assert "Type" in kwargs obj.stop() def test_human_logs(self): obj = PushLogger.setup_logging("Autopush", log_format="text") obj._output = mock_stdout = Mock() log.info("omg!", Type=7) - eq_(len(mock_stdout.mock_calls), 2) + assert len(mock_stdout.mock_calls) == 2 mock_stdout.reset_mock() log.error("wtf!", Type=7) - eq_(len(mock_stdout.mock_calls), 2) + assert len(mock_stdout.mock_calls) == 2 obj.stop() def test_start_stop(self): @@ -149,7 +148,7 @@ def test_file_output(self): obj.stop() with open("testfile.txt") as f: lines = f.readlines() - eq_(len(lines), 1) + assert len(lines) == 1 @patch("autopush.logging.boto3") def test_firehose_only_output(self, mock_boto3): @@ -159,8 +158,8 @@ def test_firehose_only_output(self, mock_boto3): obj.start() log.info("wow") obj.stop() - eq_(len(obj.firehose.mock_calls), 3) - eq_(len(obj.firehose.process.mock_calls), 1) + assert len(obj.firehose.mock_calls) == 3 + assert len(obj.firehose.process.mock_calls) == 1 class FirehoseProcessorTestCase(twisted.trial.unittest.TestCase): @@ -175,10 +174,10 @@ def tearDown(self): def test_full_queue(self): proc = FirehoseProcessor("test", 1) proc.process("test") - eq_(proc._records.full(), True) + assert proc._records.full() is True proc.process("another") - eq_(proc._records.qsize(), 1) - eq_(proc._records.get(), "test") + assert proc._records.qsize() == 1 + assert proc._records.get() == "test" def test_message_max_size(self): proc = FirehoseProcessor("test") @@ -191,8 +190,8 @@ def test_message_max_size(self): proc.start() proc.process("a decently larger message") proc.stop() - eq_(len(self.mock_boto.mock_calls), 2) - eq_(len(proc._client.put_record_batch.mock_calls), 1) + assert len(self.mock_boto.mock_calls) == 2 + assert len(proc._client.put_record_batch.mock_calls) == 1 def test_message_max_batch(self): proc = FirehoseProcessor("test") @@ -205,8 +204,8 @@ def test_message_max_batch(self): proc.start() proc.process("a decently larger message") proc.stop() - eq_(len(self.mock_boto.mock_calls), 2) - eq_(len(proc._client.put_record_batch.mock_calls), 1) + assert len(self.mock_boto.mock_calls) == 2 + assert len(proc._client.put_record_batch.mock_calls) == 1 def test_queue_timeout(self): proc = FirehoseProcessor("test") @@ -230,5 +229,5 @@ def test_batch_send_failure(self): proc.start() proc.process("a decently larger message") proc.stop() - eq_(len(self.mock_boto.mock_calls), 4) - eq_(len(proc._client.put_record_batch.mock_calls), 3) + assert len(self.mock_boto.mock_calls) == 4 + assert len(proc._client.put_record_batch.mock_calls) == 3 diff --git a/autopush/tests/test_main.py b/autopush/tests/test_main.py index f8923990..71d9fe5c 100644 --- a/autopush/tests/test_main.py +++ b/autopush/tests/test_main.py @@ -3,11 +3,7 @@ import json from mock import Mock, patch -from nose.tools import ( - assert_raises, - eq_, - ok_ -) +import pytest from twisted.internet.defer import Deferred from twisted.trial import unittest as trialtest import hyper @@ -34,13 +30,13 @@ def test_resolve_host(self): ip = resolve_ip("example.com") conf = AutopushConfig( hostname="example.com", resolve_hostname=True) - eq_(conf.hostname, ip) + assert conf.hostname == ip @patch("autopush.utils.socket") def test_resolve_host_no_interface(self, mock_socket): mock_socket.getaddrinfo.return_value = "" ip = resolve_ip("example.com") - eq_(ip, "example.com") + assert ip == "example.com" def test_new_month(self): today = datetime.date.today() @@ -56,7 +52,7 @@ def test_new_month(self): db._tomorrow = Mock() db._tomorrow.return_value = tomorrow db.create_initial_message_tables() - eq_(len(db.message_tables), 3) + assert len(db.message_tables) == 3 class ConfigAsyncTestCase(trialtest.TestCase): @@ -83,8 +79,8 @@ def test_update_rotating_tables(self): d = db.update_rotating_tables() def check_tables(result): - eq_(len(db.message_tables), 2) - eq_(db.current_month, get_month().month) + assert len(db.message_tables) == 2 + assert db.current_month == get_month().month d.addCallback(check_tables) d.addBoth(lambda x: e.callback(True)) @@ -124,7 +120,7 @@ def test_update_rotating_tables_month_end(self): db.create_initial_message_tables() # We should have 3 tables, one for next/this/last month - eq_(len(db.message_tables), 3) + assert len(db.message_tables) == 3 # Grab next month's table name and remove it next_month = get_rotating_message_table( @@ -137,8 +133,8 @@ def test_update_rotating_tables_month_end(self): d = db.update_rotating_tables() def check_tables(result): - eq_(len(db.message_tables), 3) - ok_(next_month.table_name in db.message_tables) + assert len(db.message_tables) == 3 + assert next_month.table_name in db.message_tables d.addCallback(check_tables) return d @@ -164,7 +160,7 @@ def test_update_not_needed(self): d = db.update_rotating_tables() def check_tables(result): - eq_(len(db.message_tables), 1) + assert len(db.message_tables) == 1 d.addCallback(check_tables) d.addBoth(lambda x: e.callback(True)) @@ -208,11 +204,11 @@ def test_skip_logging(self): # Should skip setting up logging on the handler mock_handler = Mock() skip_request_logging(mock_handler) - eq_(len(mock_handler.mock_calls), 0) + assert len(mock_handler.mock_calls) == 0 class EndpointMainTestCase(unittest.TestCase): - class TestArg: + class TestArg(AutopushConfig): # important stuff apns_creds = json.dumps({"firefox": {"cert": "cert.file", "key": "key.file"}}) @@ -295,13 +291,13 @@ def test_bad_senderidlist(self): "--gcm_enabled", "--senderid_list='[Invalid'" ], False) - ok_(returncode not in (None, 0)) + assert returncode not in (None, 0) def test_bad_apnsconf(self): returncode = endpoint_main([ "--apns_creds='[Invalid'" ], False) - ok_(returncode not in (None, 0)) + assert returncode not in (None, 0) def test_client_certs(self): cert = self.TestArg._client_certs['partner1'][0] @@ -310,7 +306,7 @@ def test_client_certs(self): "--ssl_key=keys/server.key", '--client_certs={"foo": ["%s"]}' % cert ], False) - ok_(not returncode) + assert not returncode def test_proxy_protocol_port(self): endpoint_main([ @@ -325,26 +321,23 @@ def test_memusage(self): @patch('hyper.tls', spec=hyper.tls) def test_client_certs_parse(self, mock): conf = AutopushConfig.from_argparse(self.TestArg) - eq_(conf.client_certs["1A:"*31 + "F9"], 'partner1') - eq_(conf.client_certs["2B:"*31 + "E8"], 'partner2') - eq_(conf.client_certs["3C:"*31 + "D7"], 'partner2') + assert conf.client_certs["1A:"*31 + "F9"] == 'partner1' + assert conf.client_certs["2B:"*31 + "E8"] == 'partner2' + assert conf.client_certs["3C:"*31 + "D7"] == 'partner2' def test_bad_client_certs(self): cert = self.TestArg._client_certs['partner1'][0] ssl_opts = ["--ssl_cert=keys/server.crt", "--ssl_key=keys/server.key"] - eq_(endpoint_main(ssl_opts + ["--client_certs='[Invalid'"], False), - 1) - eq_(endpoint_main( - ssl_opts + ['--client_certs={"": ["%s"]}' % cert], False), - 1) - eq_(endpoint_main( - ssl_opts + ['--client_certs={"quux": [""]}'], False), - 1) - eq_(endpoint_main( - ssl_opts + ['--client_certs={"foo": "%s"}' % cert], False), - 1) - eq_(endpoint_main(['--client_certs={"foo": ["%s"]}' % cert], False), - 1) + assert endpoint_main( + ssl_opts + ["--client_certs='[Invalid'"], False) == 1 + assert endpoint_main( + ssl_opts + ['--client_certs={"": ["%s"]}' % cert], False) == 1 + assert endpoint_main( + ssl_opts + ['--client_certs={"quux": [""]}'], False) == 1 + assert endpoint_main( + ssl_opts + ['--client_certs={"foo": "%s"}' % cert], False) == 1 + assert endpoint_main( + ['--client_certs={"foo": ["%s"]}' % cert], False) == 1 @patch('autopush.router.apns2.HTTP20Connection', spec=hyper.HTTP20Connection) @@ -353,15 +346,16 @@ def test_conf(self, *args): conf = AutopushConfig.from_argparse(self.TestArg) app = EndpointApplication(conf) # verify that the hostname is what we said. - eq_(conf.hostname, self.TestArg.hostname) - eq_(app.routers["gcm"].router_conf['collapsekey'], "collapse") - eq_(app.routers["apns"].router_conf['firefox']['cert'], "cert.file") - eq_(app.routers["apns"].router_conf['firefox']['key'], "key.file") + assert conf.hostname == self.TestArg.hostname + assert app.routers["gcm"].router_conf['collapsekey'] == "collapse" + assert app.routers["apns"].router_conf['firefox']['cert'] == \ + "cert.file" + assert app.routers["apns"].router_conf['firefox']['key'] == "key.file" def test_bad_senders(self): old_list = self.TestArg.senderid_list self.TestArg.senderid_list = "{}" - with assert_raises(InvalidConfig): + with pytest.raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.senderid_list = old_list @@ -369,11 +363,11 @@ def test_bad_fcm_senders(self): old_auth = self.TestArg.fcm_auth old_senderid = self.TestArg.fcm_senderid self.TestArg.fcm_auth = "" - with assert_raises(InvalidConfig): + with pytest.raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.fcm_auth = old_auth self.TestArg.fcm_senderid = "" - with assert_raises(InvalidConfig): + with pytest.raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.fcm_senderid = old_senderid @@ -394,4 +388,4 @@ class MockReply: request_mock.return_value = MockReply self.TestArg.no_aws = False conf = AutopushConfig.from_argparse(self.TestArg) - eq_(conf.ami_id, "ami_123") + assert conf.ami_id == "ami_123" diff --git a/autopush/tests/test_metrics.py b/autopush/tests/test_metrics.py index 8e10d704..ef33896a 100644 --- a/autopush/tests/test_metrics.py +++ b/autopush/tests/test_metrics.py @@ -2,7 +2,7 @@ import twisted.internet.base -from nose.tools import assert_raises, ok_, eq_ +import pytest from mock import Mock, patch from autopush.metrics import ( @@ -17,18 +17,21 @@ class IMetricsTestCase(unittest.TestCase): def test_default(self): im = IMetrics() im.start() - assert_raises(NotImplementedError, im.increment, "test") - assert_raises(NotImplementedError, im.gauge, "test", 10) - assert_raises(NotImplementedError, im.timing, "test", 10) + with pytest.raises(NotImplementedError): + im.increment("test") + with pytest.raises(NotImplementedError): + im.gauge("test", 10) + with pytest.raises(NotImplementedError): + im.timing("test", 10) class SinkMetricsTestCase(unittest.TestCase): def test_passing(self): sm = SinkMetrics() sm.start() - eq_(None, sm.increment("test")) - eq_(None, sm.gauge("test", 10)) - eq_(None, sm.timing("test", 10)) + assert sm.increment("test") is None + assert sm.gauge("test", 10) is None + assert sm.timing("test", 10) is None class TwistedMetricsTestCase(unittest.TestCase): @@ -37,7 +40,7 @@ def test_basic(self, mock_reactor): twisted.internet.base.DelayedCall.debug = True m = TwistedMetrics('127.0.0.1') m.start() - ok_(len(mock_reactor.mock_calls) > 0) + assert len(mock_reactor.mock_calls) > 0 m._metric = Mock() m.increment("test", 5) m._metric.increment.assert_called_with("test", 5) @@ -54,7 +57,7 @@ def test_basic(self, mock_dog): m = DatadogMetrics("someapikey", "someappkey", namespace="testpush", hostname="localhost") - ok_(len(mock_dog.mock_calls) > 0) + assert len(mock_dog.mock_calls) > 0 m._client = Mock() m.start() m._client.start.assert_called_with(flush_interval=10, diff --git a/autopush/tests/test_router.py b/autopush/tests/test_router.py index 2dc9a4bc..9aa333e0 100644 --- a/autopush/tests/test_router.py +++ b/autopush/tests/test_router.py @@ -7,7 +7,7 @@ from autopush.utils import WebPushNotification from mock import Mock, PropertyMock, patch -from nose.tools import eq_, ok_, assert_raises +import pytest from twisted.trial import unittest from twisted.internet.error import ConnectionRefusedError from twisted.internet.defer import inlineCallbacks @@ -38,15 +38,19 @@ class RouterInterfaceTestCase(TestCase): def test_not_implemented(self): - assert_raises(NotImplementedError, IRouter, None, None) + with pytest.raises(NotImplementedError): + IRouter(None, None) def init(self, conf, router_conf): pass IRouter.__init__ = init ir = IRouter(None, None) - assert_raises(NotImplementedError, ir.register, "uaid", {}, "") - assert_raises(NotImplementedError, ir.route_notification, "uaid", {}) - assert_raises(NotImplementedError, ir.amend_endpoint_response, {}, {}) + with pytest.raises(NotImplementedError): + ir.register("uaid", {}, "") + with pytest.raises(NotImplementedError): + ir.route_notification("uaid", {}) + with pytest.raises(NotImplementedError): + ir.amend_endpoint_response({}, {}) # FOR LEGACY REASONS, CHANNELID MUST BE IN HEX FORMAT FOR BRIDGE PUBLICATION @@ -114,23 +118,27 @@ def setUp(self, mt, mc): def test_register(self): router_data = {"token": "connect_data"} - self.router.register("uaid", router_data=router_data, app_id="firefox") - eq_(router_data, {"rel_channel": "firefox", "token": "connect_data"}) + self.router.register("uaid", router_data=router_data, + app_id="firefox") + assert router_data == {"rel_channel": "firefox", + "token": "connect_data"} def test_extended_register(self): router_data = {"token": "connect_data", "aps": {"foo": "bar", "gorp": "baz"}} - self.router.register("uaid", router_data=router_data, app_id="firefox") - eq_(router_data, {"rel_channel": "firefox", "token": "connect_data", - "aps": {"foo": "bar", "gorp": "baz"}}) + self.router.register("uaid", router_data=router_data, + app_id="firefox") + assert router_data == { + "rel_channel": "firefox", "token": "connect_data", + "aps": {"foo": "bar", "gorp": "baz"}} def test_register_bad(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register("uaid", router_data={}, app_id="firefox") def test_register_bad_channel(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register( "uaid", router_data={"token": "connect_data"}, @@ -146,12 +154,12 @@ def raiser(*args, **kwargs): self.router.apns['firefox'].connections[1].request = Mock( side_effect=raiser) - with assert_raises(RouterException) as e: + with pytest.raises(RouterException) as ex: yield self.router.route_notification(self.notif, self.router_data) - eq_(e.exception.response_body, 'APNS returned an error ' - 'processing request') - eq_(e.exception.status_code, 502) + assert ex.value.response_body == ('APNS returned an error ' + 'processing request') + assert ex.value.status_code == 502 self.flushLoggedErrors() @inlineCallbacks @@ -161,14 +169,14 @@ def test_route_notification(self): yield self._waitfor(lambda: self.mock_connection.request.called is True) - ok_(isinstance(result, RouterResponse)) - ok_(self.mock_connection.request.called) + assert isinstance(result, RouterResponse) + assert self.mock_connection.request.called body = self.mock_connection.request.call_args[1] body_json = json.loads(body['body']) - ok_('chid' in body_json) + assert 'chid' in body_json # The ChannelID is a UUID4, and unpredictable. del(body_json['chid']) - eq_(body_json, { + assert body_json == { "body": "q60d6g", "enc": "test", "ver": 10, @@ -178,7 +186,7 @@ def test_route_notification(self): }, "enckey": "test", "con": "aesgcm", - }) + } @inlineCallbacks def test_route_notification_complex(self): @@ -192,12 +200,12 @@ def test_route_notification_complex(self): router_data) yield self._waitfor(lambda: self.mock_connection.request.called is True) - ok_(isinstance(result, RouterResponse)) - ok_(self.mock_connection.request.called) + assert isinstance(result, RouterResponse) + assert self.mock_connection.request.called body = self.mock_connection.request.call_args[1] body_json = json.loads(body['body']) - eq_(body_json['aps']['number'], 4) - eq_(body_json['aps']['string'], 'String') + assert body_json['aps']['number'] == 4 + assert body_json['aps']['string'] == 'String' @inlineCallbacks def test_route_low_priority_notification(self): @@ -208,25 +216,26 @@ def test_route_low_priority_notification(self): yield apns2.send("abcd0123", {}, 'apnsid', priority=False, exp=exp) yield self._waitfor(lambda: self.mock_connection.request.called is True) - ok_(self.mock_connection.request.called) + assert self.mock_connection.request.called body = self.mock_connection.request.call_args[1] headers = body['headers'] - eq_(headers, {'apns-expiration': str(exp), - 'apns-topic': 'com.example.SomeApp', - 'apns-priority': '5', - 'apns-id': 'apnsid'}) + assert headers == { + 'apns-expiration': str(exp), + 'apns-topic': 'com.example.SomeApp', + 'apns-priority': '5', + 'apns-id': 'apnsid'} @inlineCallbacks def test_bad_send(self): self.mock_response.status = 400 self.mock_response.read.return_value = json.dumps({'reason': 'boo'}) - with assert_raises(RouterException) as ex: + with pytest.raises(RouterException) as ex: yield self.router.route_notification(self.notif, self.router_data) - ok_(isinstance(ex.exception, RouterException)) - eq_(ex.exception.status_code, 502) - eq_(ex.exception.message, 'APNS Transmit Error 400:boo') - eq_(ex.exception.response_body, 'APNS could not process your ' - 'message boo') + assert isinstance(ex.value, RouterException) + assert ex.value.status_code == 502 + assert ex.value.message == 'APNS Transmit Error 400:boo' + assert ex.value.response_body == ( + 'APNS could not process your message boo') @inlineCallbacks def test_fail_send(self): @@ -234,32 +243,32 @@ def throw(*args, **kwargs): raise HTTP20Error("oops") self.router.apns['firefox'].connections[0].request.side_effect = throw - with assert_raises(RouterException) as ex: + with pytest.raises(RouterException) as ex: yield self.router.route_notification(self.notif, self.router_data) - ok_(isinstance(ex.exception, RouterException)) - eq_(ex.exception.status_code, 502) - eq_(ex.exception.message, "Server error") - eq_(ex.exception.response_body, 'APNS returned an error processing ' - 'request') + assert isinstance(ex.value, RouterException) + assert ex.value.status_code == 502 + assert ex.value.message == "Server error" + assert ex.value.response_body == 'APNS returned an error ' \ + 'processing request' self.flushLoggedErrors() def test_too_many_connections(self): rr = self.router.apns['firefox'] - with assert_raises(RouterException) as ex: + with pytest.raises(RouterException) as ex: while True: rr._get_connection() - ok_(isinstance(ex.exception, RouterException)) - eq_(ex.exception.status_code, 503) - eq_(ex.exception.message, "Too many APNS requests, " - "increase pool from 2") - eq_(ex.exception.response_body, "APNS busy, please retry") + assert isinstance(ex.value, RouterException) + assert ex.value.status_code == 503 + assert ex.value.message == "Too many APNS requests, " \ + "increase pool from 2" + assert ex.value.response_body == "APNS busy, please retry" def test_amend(self): resp = {"key": "value"} expected = resp.copy() self.router.amend_endpoint_response(resp, {}) - eq_(resp, expected) + assert resp == expected def test_route_crypto_key(self): headers = {"content-encoding": "aesgcm", @@ -277,11 +286,11 @@ def test_route_crypto_key(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) - eq_(result.logged_status, 200) - ok_("TTL" in result.headers) - ok_(self.mock_connection.called) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 + assert result.logged_status == 200 + assert "TTL" in result.headers + assert self.mock_connection.called d.addCallback(check_results) return d @@ -327,11 +336,11 @@ def setUp(self, fgcm): fgcm.send.return_value = mock_result def _check_error_call(self, exc, code, response=None): - ok_(isinstance(exc, RouterException)) - eq_(exc.status_code, code) - ok_(self.router.gcm['test123'].send.called) + assert isinstance(exc, RouterException) + assert exc.status_code == code + assert self.router.gcm['test123'].send.called if response: - eq_(exc.response_body, response) + assert exc.response_body == response self.flushLoggedErrors() def test_init(self): @@ -339,23 +348,24 @@ def test_init(self): hostname="localhost", statsd_host=None, ) - with assert_raises(IOError): + with pytest.raises(IOError): GCMRouter(conf, {"senderIDs": {}}, SinkMetrics()) def test_register(self): router_data = {"token": "test123"} self.router.register("uaid", router_data=router_data, app_id="test123") # Check the information that will be recorded for this user - eq_(router_data, {"token": "test123", - "creds": {"senderID": "test123", - "auth": "12345678abcdefg"}}) + assert router_data == { + "token": "test123", + "creds": {"senderID": "test123", + "auth": "12345678abcdefg"}} def test_register_bad(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register("uaid", router_data={}, app_id="") - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register("uaid", router_data={}, app_id='') - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register( "uaid", router_data={"token": "abcd1234"}, @@ -368,7 +378,7 @@ def test_gcmclient_fail(self, fgcm): hostname="localhost", statsd_host=None, ) - with assert_raises(IOError): + with pytest.raises(IOError): GCMRouter( conf, {"senderIDs": {"test123": {"auth": "abcd"}}}, @@ -380,15 +390,15 @@ def test_route_notification(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.gcm['test123'].send.called) + assert isinstance(result, RouterResponse) + assert self.router.gcm['test123'].send.called # Make sure the data was encoded as base64 data = self.router.gcm['test123'].send.call_args[0][0].data - eq_(data['body'], 'q60d6g') - eq_(data['enc'], 'test') - eq_(data['chid'], dummy_chid) - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['enc'] == 'test' + assert data['chid'] == dummy_chid + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' d.addCallback(check_results) return d @@ -405,21 +415,21 @@ def test_ttl_none(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) - eq_(result.logged_status, 200) - ok_("TTL" in result.headers) - ok_(self.router.gcm['test123'].send.called) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 + assert result.logged_status == 200 + assert "TTL" in result.headers + assert self.router.gcm['test123'].send.called # Make sure the data was encoded as base64 data = self.router.gcm['test123'].send.call_args[0][0].data options = self.router.gcm['test123'].send.call_args[0][0].options - eq_(data['body'], 'q60d6g') - eq_(data['enc'], 'test') - eq_(data['chid'], dummy_chid) - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['enc'] == 'test' + assert data['chid'] == dummy_chid + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' # use the defined min TTL - eq_(options['time_to_live'], 60) + assert options['time_to_live'] == 60 d.addCallback(check_results) return d @@ -436,18 +446,18 @@ def test_ttl_high(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.gcm['test123'].send.called) + assert isinstance(result, RouterResponse) + assert self.router.gcm['test123'].send.called # Make sure the data was encoded as base64 data = self.router.gcm['test123'].send.call_args[0][0].data options = self.router.gcm['test123'].send.call_args[0][0].options - eq_(data['body'], 'q60d6g') - eq_(data['enc'], 'test') - eq_(data['chid'], dummy_chid) - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['enc'] == 'test' + assert data['chid'] == dummy_chid + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' # use the defined min TTL - eq_(options['time_to_live'], 2419200) + assert options['time_to_live'] == 2419200 d.addCallback(check_results) return d @@ -464,9 +474,9 @@ def test_long_data(self): d = self.router.route_notification(bad_notif, self.router_data) def check_results(result): - ok_(isinstance(result.value, RouterException)) - eq_(result.value.status_code, 413) - eq_(result.value.errno, 104) + assert isinstance(result.value, RouterException) + assert result.value.status_code == 413 + assert result.value.errno == 104 d.addBoth(check_results) return d @@ -478,8 +488,8 @@ def test_route_crypto_notification(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.gcm['test123'].send.called) + assert isinstance(result, RouterResponse) + assert self.router.gcm['test123'].send.called d.addCallback(check_results) return d @@ -529,14 +539,14 @@ def test_router_notification_gcm_id_change(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.router_data, dict(token="new")) - eq_(self.router.metrics.increment.call_args[0][0], + assert isinstance(result, RouterResponse) + assert result.router_data == dict(token="new") + assert self.router.metrics.increment.call_args[0][0] == ( 'notification.bridge.error') self.router.metrics.increment.call_args[1]['tags'].sort() - eq_(self.router.metrics.increment.call_args[1]['tags'], - ['platform:gcm', 'reason:reregister']) - ok_(self.router.gcm['test123'].send.called) + assert self.router.metrics.increment.call_args[1]['tags'] == [ + 'platform:gcm', 'reason:reregister'] + assert self.router.gcm['test123'].send.called d.addCallback(check_results) return d @@ -547,14 +557,14 @@ def test_router_notification_gcm_not_regged(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.router_data, dict()) - eq_(self.router.metrics.increment.call_args[0][0], + assert isinstance(result, RouterResponse) + assert result.router_data == dict() + assert self.router.metrics.increment.call_args[0][0] == ( 'notification.bridge.error') self.router.metrics.increment.call_args[1]['tags'].sort() - eq_(self.router.metrics.increment.call_args[1]['tags'], - ['platform:gcm', 'reason:unregistered']) - ok_(self.router.gcm['test123'].send.called) + assert self.router.metrics.increment.call_args[1]['tags'] == [ + 'platform:gcm', 'reason:unregistered'] + assert self.router.gcm['test123'].send.called d.addCallback(check_results) return d @@ -565,13 +575,13 @@ def test_router_notification_gcm_failed_items(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(fail): - ok_(self.router.metrics.increment.called) - eq_(self.router.metrics.increment.call_args[0][0], + assert self.router.metrics.increment.called + assert self.router.metrics.increment.call_args[0][0] == ( 'notification.bridge.error') self.router.metrics.increment.call_args[1]['tags'].sort() - eq_(self.router.metrics.increment.call_args[1]['tags'], - ['platform:gcm', 'reason:failure']) - eq_(fail.value.message, 'GCM unable to deliver') + assert self.router.metrics.increment.call_args[1]['tags'] == [ + 'platform:gcm', 'reason:failure'] + assert fail.value.message == 'GCM unable to deliver' self._check_error_call(fail.value, 410) d.addBoth(check_results) return d @@ -583,13 +593,13 @@ def test_router_notification_gcm_needs_retry(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(fail): - ok_(self.router.metrics.increment.called) - eq_(self.router.metrics.increment.call_args[0][0], + assert self.router.metrics.increment.called + assert self.router.metrics.increment.call_args[0][0] == ( 'notification.bridge.error') self.router.metrics.increment.call_args[1]['tags'].sort() - eq_(self.router.metrics.increment.call_args[1]['tags'], - ['platform:gcm', 'reason:retry']) - eq_(fail.value.message, 'GCM failure to deliver, retry') + assert self.router.metrics.increment.call_args[1]['tags'] == [ + 'platform:gcm', 'reason:retry'] + assert fail.value.message == 'GCM failure to deliver, retry' self._check_error_call(fail.value, 503) d.addBoth(check_results) return d @@ -599,20 +609,21 @@ def test_router_notification_gcm_no_auth(self): {"router_data": {"token": "abc"}}) def check_results(fail): - eq_(fail.value.status_code, 500, "Server error") + assert fail.value.status_code == 500, "Server error" d.addBoth(check_results) return d def test_amend(self): router_data = {"token": "test123"} - self.router.register("uaid", router_data=router_data, app_id="test123") + self.router.register("uaid", router_data=router_data, + app_id="test123") resp = {"key": "value"} self.router.amend_endpoint_response( resp, self.router_data.get('router_data')) - eq_({"key": "value", "senderid": "test123"}, resp) + assert {"key": "value", "senderid": "test123"} == resp def test_register_invalid_token(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register( uaid="uaid", router_data={"token": "invalid"}, @@ -660,9 +671,9 @@ def setUp(self, ffcm): ffcm.notify_single_device.return_value = mock_result def _check_error_call(self, exc, code): - ok_(isinstance(exc, RouterException)) - eq_(exc.status_code, code) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(exc, RouterException) + assert exc.status_code == code + assert self.router.fcm.notify_single_device.called self.flushLoggedErrors() @patch("pyfcm.FCMNotification", spec=pyfcm.FCMNotification) @@ -676,19 +687,21 @@ def throw_auth(*args, **kwargs): raise Exception("oopsy") ffcm.side_effect = throw_auth - with assert_raises(IOError): + with pytest.raises(IOError): FCMRouter(conf, {}, SinkMetrics()) def test_register(self): router_data = {"token": "test123"} - self.router.register("uaid", router_data=router_data, app_id="test123") + self.router.register("uaid", router_data=router_data, + app_id="test123") # Check the information that will be recorded for this user - eq_(router_data, {"token": "test123", - "creds": {"senderID": "test123", - "auth": "12345678abcdefg"}}) + assert router_data == { + "token": "test123", + "creds": {"senderID": "test123", + "auth": "12345678abcdefg"}} def test_register_bad(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register("uaid", router_data={}, app_id="invalid123") def test_route_notification(self): @@ -696,19 +709,19 @@ def test_route_notification(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) - eq_(result.logged_status, 200) - ok_("TTL" in result.headers) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 + assert result.logged_status == 200 + assert "TTL" in result.headers + assert self.router.fcm.notify_single_device.called # Make sure the data was encoded as base64 args = self.router.fcm.notify_single_device.call_args[1] data = args['data_message'] - eq_(data['body'], 'q60d6g') - eq_(data['chid'], dummy_chid) - eq_(data['enc'], 'test') - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['chid'] == dummy_chid + assert data['enc'] == 'test' + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' d.addCallback(check_results) return d @@ -725,18 +738,18 @@ def test_ttl_none(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert self.router.fcm.notify_single_device.called # Make sure the data was encoded as base64 args = self.router.fcm.notify_single_device.call_args[1] data = args['data_message'] - eq_(data['body'], 'q60d6g') - eq_(data['chid'], dummy_chid) - eq_(data['enc'], 'test') - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['chid'] == dummy_chid + assert data['enc'] == 'test' + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' # use the defined min TTL - eq_(args['time_to_live'], 60) + assert args['time_to_live'] == 60 d.addCallback(check_results) return d @@ -753,18 +766,18 @@ def test_ttl_high(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert self.router.fcm.notify_single_device.called # Make sure the data was encoded as base64 args = self.router.fcm.notify_single_device.call_args[1] data = args['data_message'] - eq_(data['body'], 'q60d6g') - eq_(data['chid'], dummy_chid) - eq_(data['enc'], 'test') - eq_(data['enckey'], 'test') - eq_(data['con'], 'aesgcm') + assert data['body'] == 'q60d6g' + assert data['chid'] == dummy_chid + assert data['enc'] == 'test' + assert data['enckey'] == 'test' + assert data['con'] == 'aesgcm' # use the defined min TTL - eq_(args['time_to_live'], 2419200) + assert args['time_to_live'] == 2419200 d.addCallback(check_results) return d @@ -782,9 +795,9 @@ def test_long_data(self): d = self.router.route_notification(bad_notif, self.router_data) def check_results(result): - ok_(isinstance(result.value, RouterException)) - eq_(result.value.status_code, 413) - eq_(result.value.errno, 104) + assert isinstance(result.value, RouterException) + assert result.value.status_code == 413 + assert result.value.errno == 104 d.addBoth(check_results) return d @@ -796,8 +809,8 @@ def test_route_crypto_notification(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert self.router.fcm.notify_single_device.called d.addCallback(check_results) return d @@ -847,9 +860,9 @@ def test_router_notification_fcm_id_change(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.router_data, dict(token="new")) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert result.router_data == dict(token="new") + assert self.router.fcm.notify_single_device.called d.addCallback(check_results) return d @@ -860,9 +873,9 @@ def test_router_notification_fcm_not_regged(self): d = self.router.route_notification(self.notif, self.router_data) def check_results(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.router_data, dict()) - ok_(self.router.fcm.notify_single_device.called) + assert isinstance(result, RouterResponse) + assert result.router_data == dict() + assert self.router.fcm.notify_single_device.called d.addCallback(check_results) return d @@ -883,7 +896,7 @@ def test_router_notification_fcm_no_auth(self): {"router_data": {"token": ""}}) def check_results(fail): - eq_(fail.value.status_code, 410) + assert fail.value.status_code == 410 d.addBoth(check_results) return d @@ -894,10 +907,10 @@ def test_amend(self): resp = {"key": "value"} self.router.amend_endpoint_response( resp, self.router_data.get('router_data')) - eq_({"key": "value", "senderid": "test123"}, resp) + assert {"key": "value", "senderid": "test123"} == resp def test_register_invalid_token(self): - with assert_raises(RouterException): + with pytest.raises(RouterException): self.router.register( uaid="uaid", router_data={"token": "invalid"}, @@ -953,14 +966,14 @@ def test_route_to_busy_node_saves_looks_up_and_sends_check_201(self): d = self.router.route_notification(self.notif, router_data) def verify_deliver(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 kwargs = self.message_mock.store_message.call_args[1] t_h = kwargs["notification"].headers - eq_(t_h.get('encryption'), self.headers.get('encryption')) - eq_(t_h.get('crypto_key'), self.headers.get('crypto-key')) - eq_(t_h.get('encoding'), self.headers.get('content-encoding')) - ok_("Location" in result.headers) + assert t_h.get('encryption') == self.headers.get('encryption') + assert t_h.get('crypto_key') == self.headers.get('crypto-key') + assert t_h.get('encoding') == self.headers.get('content-encoding') + assert "Location" in result.headers d.addCallback(verify_deliver) return d @@ -977,15 +990,15 @@ def test_route_failure(self): d = self.router.route_notification(self.notif, router_data) def verify_deliver(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 kwargs = self.message_mock.store_message.call_args[1] - eq_(len(self.metrics.increment.mock_calls), 3) + assert len(self.metrics.increment.mock_calls) == 3 t_h = kwargs["notification"].headers - eq_(t_h.get('encryption'), self.headers.get('encryption')) - eq_(t_h.get('crypto_key'), self.headers.get('crypto-key')) - eq_(t_h.get('encoding'), self.headers.get('content-encoding')) - ok_("Location" in result.headers) + assert t_h.get('encryption') == self.headers.get('encryption') + assert t_h.get('crypto_key') == self.headers.get('crypto-key') + assert t_h.get('encoding') == self.headers.get('content-encoding') + assert "Location" in result.headers d.addCallback(verify_deliver) return d @@ -1015,10 +1028,10 @@ def test_route_to_busy_node_with_ttl_zero(self): def verify_deliver(fail): exc = fail.value - ok_(exc, RouterResponse) - eq_(exc.status_code, 201) - eq_(len(self.metrics.increment.mock_calls), 0) - ok_("Location" in exc.headers) + assert isinstance(exc, RouterException) + assert exc.status_code == 201 + assert len(self.metrics.increment.mock_calls) == 0 + assert "Location" in exc.headers d.addBoth(verify_deliver) return d @@ -1026,7 +1039,7 @@ def test_amend(self): resp = {"key": "value"} expected = resp.copy() self.router.amend_endpoint_response(resp, {}) - eq_(resp, expected) + assert resp == expected def test_route_to_busy_node_save_throws_db_error(self): from boto.dynamodb2.exceptions import JSONResponseError @@ -1046,8 +1059,8 @@ def throw(): def verify_deliver(fail): exc = fail.value - ok_(exc, RouterException) - eq_(exc.status_code, 503) + assert isinstance(exc, RouterException) + assert exc.status_code == 503 d.addBoth(verify_deliver) return d @@ -1068,7 +1081,7 @@ def throw(): d = self.router.route_notification(self.notif, router_data) def verify_deliver(status): - ok_(status.status_code, 201) + assert status.status_code == 201 d.addBoth(verify_deliver) return d @@ -1089,7 +1102,7 @@ def throw(): d = self.router.route_notification(self.notif, router_data) def verify_deliver(status): - ok_(status.value.status_code, 410) + assert status.value.status_code == 410 d.addBoth(verify_deliver) return d @@ -1105,7 +1118,7 @@ def test_route_lookup_uaid_no_nodeid(self): d = self.router.route_notification(self.notif, router_data) def verify_deliver(status): - ok_(status.status_code, 201) + assert status.status_code == 201 d.addBoth(verify_deliver) return d @@ -1128,15 +1141,15 @@ def throw(): d = self.router.route_notification(self.notif, router_data) def verify_deliver(result): - ok_(isinstance(result, RouterResponse)) - eq_(result.status_code, 201) + assert isinstance(result, RouterResponse) + assert result.status_code == 201 kwargs = self.message_mock.store_message.call_args[1] - eq_(len(self.metrics.increment.mock_calls), 3) + assert len(self.metrics.increment.mock_calls) == 3 t_h = kwargs["notification"].headers - eq_(t_h.get('encryption'), self.headers.get('encryption')) - eq_(t_h.get('crypto_key'), self.headers.get('crypto-key')) - eq_(t_h.get('encoding'), self.headers.get('content-encoding')) - ok_("Location" in result.headers) + assert t_h.get('encryption') == self.headers.get('encryption') + assert t_h.get('crypto_key') == self.headers.get('crypto-key') + assert t_h.get('encoding') == self.headers.get('content-encoding') + assert "Location" in result.headers d.addCallback(verify_deliver) return d diff --git a/autopush/tests/test_utils.py b/autopush/tests/test_utils.py index 6fa15fa3..89ca5279 100644 --- a/autopush/tests/test_utils.py +++ b/autopush/tests/test_utils.py @@ -1,7 +1,6 @@ import unittest from mock import patch, Mock -from nose.tools import eq_ from autopush.tests.test_integration import _get_vapid @@ -13,31 +12,31 @@ def _makeFUT(self, *args): def test_linux_extraction(self): dd, raw = self._makeFUT('Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.2) Gecko/20090807 Mandriva Linux/1.9.1.2-1.1mud2009.1 (2009.1) Firefox/3.5.2 FirePHP/0.3,gzip(gfe),gzip(gfe)') # NOQA - eq_(dd["ua_os_family"], "Linux") - eq_(raw["ua_os_family"], "Mandriva") + assert dd["ua_os_family"] == "Linux" + assert raw["ua_os_family"] == "Mandriva" def test_windows_extraction(self): dd, raw = self._makeFUT('Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729)') # NOQA - eq_(dd["ua_os_family"], "Windows") - eq_(raw["ua_os_family"], "Windows 7") + assert dd["ua_os_family"] == "Windows" + assert raw["ua_os_family"] == "Windows 7" def test_valid_os(self): dd, raw = self._makeFUT('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:2.1.1) Gecko/ Firefox/5.0.1') # NOQA - eq_(dd["ua_os_family"], "Mac OS X") - eq_(raw["ua_os_family"], "Mac OS X") + assert dd["ua_os_family"] == "Mac OS X" + assert raw["ua_os_family"] == "Mac OS X" def test_other_os_and_browser(self): dd, raw = self._makeFUT('BlackBerry9000/4.6.0.167 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/102') # NOQA - eq_(dd["ua_os_family"], "Other") - eq_(raw["ua_os_family"], "BlackBerry OS") - eq_(dd["ua_browser_family"], "Other") - eq_(raw["ua_browser_family"], "BlackBerry") + assert dd["ua_os_family"] == "Other" + assert raw["ua_os_family"] == "BlackBerry OS" + assert dd["ua_browser_family"] == "Other" + assert raw["ua_browser_family"] == "BlackBerry" def test_trusted_vapid(self): from autopush.utils import extract_jwt vapid_info = _get_vapid(payload={'sub': 'mailto:foo@example.com'}) data = extract_jwt(vapid_info['auth'], 'invalid_key', is_trusted=True) - eq_(data['sub'], 'mailto:foo@example.com') + assert data['sub'] == 'mailto:foo@example.com' @patch("requests.get") def test_get_amid_unknown(self, request_mock): @@ -46,7 +45,7 @@ def test_get_amid_unknown(self, request_mock): request_mock.side_effect = requests.HTTPError result = get_amid() - eq_(result, "Unknown") + assert result == "Unknown" @patch("requests.get") def test_get_ec2_instance_id_unknown(self, request_mock): @@ -55,7 +54,7 @@ def test_get_ec2_instance_id_unknown(self, request_mock): request_mock.side_effect = requests.HTTPError result = get_ec2_instance_id() - eq_(result, "Unknown") + assert result == "Unknown" @patch("requests.get") def test_get_ec2_instance_id(self, request_mock): @@ -65,4 +64,4 @@ def test_get_ec2_instance_id(self, request_mock): request_mock.return_value = mock_reply result = get_ec2_instance_id() - eq_(result, "i-123242") + assert result == "i-123242" diff --git a/autopush/tests/test_web_base.py b/autopush/tests/test_web_base.py index e9ecdfe6..d47cc187 100644 --- a/autopush/tests/test_web_base.py +++ b/autopush/tests/test_web_base.py @@ -3,7 +3,6 @@ from boto.exception import BotoServerError from mock import Mock, patch -from nose.tools import eq_, ok_ from twisted.internet.defer import Deferred from twisted.logger import Logger from twisted.python.failure import Failure @@ -70,19 +69,19 @@ def test_cors(self): ch4 = "Access-Control-Expose-Headers" base = self.base base.conf.cors = False - ok_(base._headers.get(ch1) != "*") - ok_(base._headers.get(ch2) != self.CORS_METHODS) - ok_(base._headers.get(ch3) != self.CORS_HEADERS) - ok_(base._headers.get(ch4) != self.CORS_RESPONSE_HEADERS) + assert base._headers.get(ch1) != "*" + assert base._headers.get(ch2) != self.CORS_METHODS + assert base._headers.get(ch3) != self.CORS_HEADERS + assert base._headers.get(ch4) != self.CORS_RESPONSE_HEADERS base.clear_header(ch1) base.clear_header(ch2) base.conf.cors = True self.base.prepare() - eq_(base._headers[ch1], "*") - eq_(base._headers[ch2], self.CORS_METHODS) - eq_(base._headers[ch3], self.CORS_HEADERS) - eq_(base._headers[ch4], self.CORS_RESPONSE_HEADERS) + assert base._headers[ch1] == "*" + assert base._headers[ch2] == self.CORS_METHODS + assert base._headers[ch3] == self.CORS_HEADERS + assert base._headers[ch4] == self.CORS_RESPONSE_HEADERS def test_cors_head(self): ch1 = "Access-Control-Allow-Origin" @@ -94,10 +93,10 @@ def test_cors_head(self): base.prepare() args = {"api_ver": "v1", "token": "test"} base.head(args) - eq_(base._headers[ch1], "*") - eq_(base._headers[ch2], self.CORS_METHODS) - eq_(base._headers[ch3], self.CORS_HEADERS) - eq_(base._headers[ch4], self.CORS_RESPONSE_HEADERS) + assert base._headers[ch1] == "*" + assert base._headers[ch2] == self.CORS_METHODS + assert base._headers[ch3] == self.CORS_HEADERS + assert base._headers[ch4] == self.CORS_RESPONSE_HEADERS def test_cors_options(self): ch1 = "Access-Control-Allow-Origin" @@ -111,10 +110,10 @@ def test_cors_options(self): base.conf.cors = True base.prepare() base.options(args) - eq_(base._headers[ch1], "*") - eq_(base._headers[ch2], self.CORS_METHODS) - eq_(base._headers[ch3], self.CORS_HEADERS) - eq_(base._headers[ch4], self.CORS_RESPONSE_HEADERS) + assert base._headers[ch1] == "*" + assert base._headers[ch2] == self.CORS_METHODS + assert base._headers[ch3] == self.CORS_HEADERS + assert base._headers[ch4] == self.CORS_RESPONSE_HEADERS def test_sts_max_age_header(self): args = {"api_ver": "v1", "token": "test"} @@ -123,8 +122,8 @@ def test_sts_max_age_header(self): base.prepare() base.options(args) sts_header = base._headers.get("Strict-Transport-Security") - ok_("max-age=86400" in sts_header) - ok_("includeSubDomains" in sts_header) + assert "max-age=86400" in sts_header + assert "includeSubDomains" in sts_header def test_write_error(self): """ Write error is triggered by sending the app a request @@ -142,7 +141,7 @@ class TestX(Exception): self.base.write_error(999, exc_info=exc_info) self.status_mock.assert_called_with(999) - eq_(self.base.log.failure.called, True) + assert self.base.log.failure.called is True def test_write_error_no_exc(self): """ Write error is triggered by sending the app a request @@ -152,7 +151,7 @@ def test_write_error_no_exc(self): """ self.base.write_error(999) self.status_mock.assert_called_with(999) - eq_(self.base.log.failure.called, True) + assert self.base.log.failure.called is True @patch('uuid.uuid4', return_value=uuid.UUID(dummy_request_id)) def test_init_info(self, t): @@ -162,16 +161,16 @@ def test_init_info(self, t): self.request_mock.headers["ttl"] = "0" self.request_mock.headers["authorization"] = "bearer token fred" d = self.base._init_info() - eq_(d["request_id"], dummy_request_id) - eq_(d["user_agent"], "myself") - eq_(d["remote_ip"], "local1") - eq_(d["message_ttl"], "0") - eq_(d["authorization"], "bearer token fred") + assert d["request_id"] == dummy_request_id + assert d["user_agent"] == "myself" + assert d["remote_ip"] == "local1" + assert d["message_ttl"] == "0" + assert d["authorization"] == "bearer token fred" self.request_mock.headers["x-forwarded-for"] = "local2" self.request_mock.headers["authorization"] = "webpush token barney" d = self.base._init_info() - eq_(d["remote_ip"], "local2") - eq_(d["authorization"], "webpush token barney") + assert d["remote_ip"] == "local2" + assert d["authorization"] == "webpush token barney" def test_write_response(self): self.base._write_response(400, 103, message="Fail", diff --git a/autopush/tests/test_web_validation.py b/autopush/tests/test_web_validation.py index 6e3a8113..6122eed4 100644 --- a/autopush/tests/test_web_validation.py +++ b/autopush/tests/test_web_validation.py @@ -12,7 +12,7 @@ from jose import jws from marshmallow import Schema, fields from mock import Mock, patch -from nose.tools import eq_, ok_, assert_raises +import pytest from twisted.internet.defer import inlineCallbacks from twisted.trial import unittest @@ -81,14 +81,14 @@ def _make_full(self, schema=None): def test_validate_load(self): tv, rh = self._make_full() d, errors = tv._validate_request(rh) - eq_(errors, {}) - eq_(d, {}) + assert errors == {} + assert d == {} def test_validate_invalid_schema(self): tv, rh = self._make_full(schema=InvalidSchema) d, errors = tv._validate_request(rh) - ok_("afield" in errors) - eq_(d, {}) + assert "afield" in errors + assert d == {} def test_call_func_no_error(self): mock_func = Mock() @@ -103,7 +103,7 @@ def test_call_func_error(self): result = tv._validate_request(rh) tv._call_func(result, mock_func, rh) self._mock_errors.assert_called() - eq_(len(mock_func.mock_calls), 0) + assert len(mock_func.mock_calls) == 0 @inlineCallbacks def test_decorator(self): @@ -129,7 +129,7 @@ def get(self): ) client = Client(app) resp = yield client.get('/test') - eq_(resp.content, "done") + assert resp.content == "done" class TestWebPushRequestSchema(unittest.TestCase): @@ -167,9 +167,9 @@ def test_valid_data(self): router_data=dict(creds=dict(senderID="bogus")), ) result, errors = schema.load(self._make_test_data()) - eq_(errors, {}) - ok_("notification" in result) - eq_(str(result["subscription"]["uaid"]), dummy_uaid) + assert errors == {} + assert "notification" in result + assert str(result["subscription"]["uaid"]) == dummy_uaid def test_no_headers(self): schema = self._make_fut() @@ -184,12 +184,12 @@ def test_no_headers(self): ) data = self._make_test_data(body="asdfasdf") - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(data) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) - eq_(cm.exception.message, "Unknown Content-Encoding") + assert cm.value.status_code == 400 + assert cm.value.errno == 110 + assert cm.value.message == "Unknown Content-Encoding" def test_invalid_token(self): schema = self._make_fut() @@ -199,10 +199,10 @@ def throw_item(*args, **kwargs): schema.context["conf"].parse_endpoint.side_effect = throw_item - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data()) - eq_(cm.exception.errno, 102) + assert cm.value.errno == 102 def test_invalid_fernet_token(self): schema = self._make_fut() @@ -212,10 +212,10 @@ def throw_item(*args, **kwargs): schema.context["conf"].parse_endpoint.side_effect = throw_item - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data()) - eq_(cm.exception.errno, 102) + assert cm.value.errno == 102 def test_invalid_uaid_not_found(self): schema = self._make_fut() @@ -230,10 +230,10 @@ def throw_item(*args, **kwargs): schema.context["db"].router.get_uaid.side_effect = throw_item - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data()) - eq_(cm.exception.errno, 103) + assert cm.value.errno == 103 def test_critical_failure(self): schema = self._make_fut() @@ -247,10 +247,10 @@ def test_critical_failure(self): critical_failure="Bad SenderID", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data()) - eq_(cm.exception.errno, 105) + assert cm.value.errno == 105 def test_invalid_header_combo(self): schema = self._make_fut() @@ -271,10 +271,10 @@ def test_invalid_header_combo(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.errno, 110) + assert cm.value.errno == 110 def test_invalid_header_combo_04(self): schema = self._make_fut() @@ -296,12 +296,13 @@ def test_invalid_header_combo_04(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.message, "Encryption-Key header not valid for 02 " - "or later webpush-encryption") - eq_(cm.exception.errno, 110) + assert cm.value.message == ( + "Encryption-Key header not valid for 02 " + "or later webpush-encryption") + assert cm.value.errno == 110 def test_missing_encryption_salt(self): schema = self._make_fut() @@ -322,11 +323,11 @@ def test_missing_encryption_salt(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) + assert cm.value.status_code == 400 + assert cm.value.errno == 110 def test_missing_encryption_salt_04(self): schema = self._make_fut() @@ -347,11 +348,11 @@ def test_missing_encryption_salt_04(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) + assert cm.value.status_code == 400 + assert cm.value.errno == 110 def test_missing_encryption_key_dh(self): schema = self._make_fut() @@ -372,11 +373,11 @@ def test_missing_encryption_key_dh(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) + assert cm.value.status_code == 400 + assert cm.value.errno == 110 def test_missing_crypto_key_dh(self): schema = self._make_fut() @@ -398,11 +399,11 @@ def test_missing_crypto_key_dh(self): }, body="asdfasdf", ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) + assert cm.value.status_code == 400 + assert cm.value.errno == 110 def test_invalid_data_size(self): schema = self._make_fut() @@ -418,7 +419,7 @@ def test_invalid_data_size(self): ) schema.context["conf"].max_data = 1 - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data( headers={ "content-encoding": "aesgcm", @@ -426,7 +427,7 @@ def test_invalid_data_size(self): }, body="asdfasdfasdfasdfasd")) - eq_(cm.exception.errno, 104) + assert cm.value.errno == 104 def test_invalid_data_must_have_crypto_headers(self): schema = self._make_fut() @@ -440,10 +441,10 @@ def test_invalid_data_must_have_crypto_headers(self): router_data=dict(creds=dict(senderID="bogus")), ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(self._make_test_data(body="asdfasdfasdfasdfasd")) - eq_(cm.exception.errno, 110) + assert cm.value.errno == 110 def test_valid_data_crypto_padding_stripped(self): schema = self._make_fut() @@ -469,8 +470,8 @@ def test_valid_data_crypto_padding_stripped(self): ) result, errors = schema.load(info) - eq_(errors, {}) - eq_(result["headers"]["encryption"], "salt=asdfjiasljdf") + assert errors == {} + assert result["headers"]["encryption"] == "salt=asdfjiasljdf" def test_invalid_dh_value_for_01_crypto(self): schema = self._make_fut() @@ -496,11 +497,12 @@ def test_invalid_dh_value_for_01_crypto(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.message, "dh value in Crypto-Key header not valid " + assert cm.value.status_code == 400 + assert cm.value.message == ( + "dh value in Crypto-Key header not valid " "for 01 or earlier webpush-encryption") def test_invalid_vapid_crypto_header(self): @@ -526,10 +528,10 @@ def test_invalid_vapid_crypto_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) + assert cm.value.status_code == 401 def test_invalid_topic(self): schema = self._make_fut() @@ -550,13 +552,13 @@ def test_invalid_topic(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 113) - eq_(cm.exception.message, - "Topic must be no greater than 32 characters") + assert cm.value.status_code == 400 + assert cm.value.errno == 113 + assert cm.value.message == "Topic must be no greater than " \ + "32 characters" info = self._make_test_data( headers={ @@ -564,13 +566,13 @@ def test_invalid_topic(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 113) - eq_(cm.exception.message, - "Topic must be URL and Filename safe Base64 alphabet") + assert cm.value.status_code == 400 + assert cm.value.errno == 113 + assert cm.value.message == ("Topic must be URL and Filename " + "safe Base64 alphabet") def test_no_current_month(self): schema = self._make_fut() @@ -586,12 +588,12 @@ def test_no_current_month(self): info = self._make_test_data() - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 410) - eq_(cm.exception.errno, 106) - eq_(cm.exception.message, "No such subscription") + assert cm.value.status_code == 410 + assert cm.value.errno == 106 + assert cm.value.message == "No such subscription" def test_old_current_month(self): schema = self._make_fut() @@ -609,12 +611,12 @@ def test_old_current_month(self): info = self._make_test_data() - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 410) - eq_(cm.exception.errno, 106) - eq_(cm.exception.message, "No such subscription") + assert cm.value.status_code == 410 + assert cm.value.errno == 106 + assert cm.value.message == "No such subscription" class TestWebPushRequestSchemaUsingVapid(unittest.TestCase): @@ -687,8 +689,8 @@ def test_valid_vapid_crypto_header(self): ) result, errors = schema.load(info) - eq_(errors, {}) - ok_("jwt" in result) + assert errors == {} + assert "jwt" in result def test_valid_vapid_crypto_header_webpush(self, use_crypto=False): schema = self._make_fut() @@ -719,8 +721,8 @@ def test_valid_vapid_crypto_header_webpush(self, use_crypto=False): ) result, errors = schema.load(info) - eq_(errors, {}) - ok_("jwt" in result) + assert errors == {} + assert "jwt" in result def test_valid_vapid_crypto_header_webpush_crypto(self): self.test_valid_vapid_crypto_header_webpush(use_crypto=True) @@ -752,9 +754,9 @@ def test_valid_vapid_02_crypto_header_webpush(self): ) result, errors = schema.load(info) - eq_(errors, {}) - ok_("jwt" in result) - eq_(payload, result['jwt']['jwt_data']) + assert errors == {} + assert "jwt" in result + assert payload == result['jwt']['jwt_data'] def test_valid_vapid_02_crypto_header_webpush_alt(self): schema = self._make_fut() @@ -785,9 +787,9 @@ def test_valid_vapid_02_crypto_header_webpush_alt(self): ) result, errors = schema.load(info) - eq_(errors, {}) - ok_("jwt" in result) - eq_(payload, result['jwt']['jwt_data']) + assert errors == {} + assert "jwt" in result + assert payload == result['jwt']['jwt_data'] def test_bad_vapid_02_crypto_header(self): schema = self._make_fut() @@ -816,10 +818,10 @@ def test_bad_vapid_02_crypto_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 def test_invalid_vapid_draft2_crypto_header(self): schema = self._make_fut() @@ -849,11 +851,11 @@ def test_invalid_vapid_draft2_crypto_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 @patch("autopush.web.webpush.extract_jwt") def test_invalid_vapid_crypto_header(self, mock_jwt): @@ -887,11 +889,11 @@ def test_invalid_vapid_crypto_header(self, mock_jwt): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 def test_invalid_too_far_exp_vapid_crypto_header(self): schema = self._make_fut() @@ -919,11 +921,11 @@ def test_invalid_too_far_exp_vapid_crypto_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 def test_invalid_bad_exp_vapid_crypto_header(self): schema = self._make_fut() @@ -951,11 +953,11 @@ def test_invalid_bad_exp_vapid_crypto_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 @patch("autopush.web.webpush.extract_jwt") def test_invalid_encryption_header(self, mock_jwt): @@ -987,11 +989,11 @@ def test_invalid_encryption_header(self, mock_jwt): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 @patch("autopush.web.webpush.extract_jwt") def test_invalid_encryption_jwt(self, mock_jwt): @@ -1024,11 +1026,11 @@ def test_invalid_encryption_jwt(self, mock_jwt): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 @patch("autopush.web.webpush.extract_jwt") def test_invalid_crypto_key_header_content(self, mock_jwt): @@ -1060,11 +1062,11 @@ def test_invalid_crypto_key_header_content(self, mock_jwt): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 400) - eq_(cm.exception.errno, 110) + assert cm.value.status_code == 400 + assert cm.value.errno == 110 def test_expired_vapid_header(self): schema = self._make_fut() @@ -1094,11 +1096,11 @@ def test_expired_vapid_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 def test_missing_vapid_header(self): schema = self._make_fut() @@ -1127,11 +1129,11 @@ def test_missing_vapid_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 def test_bogus_vapid_header(self): schema = self._make_fut() @@ -1162,8 +1164,8 @@ def test_bogus_vapid_header(self): } ) - with assert_raises(InvalidRequest) as cm: + with pytest.raises(InvalidRequest) as cm: schema.load(info) - eq_(cm.exception.status_code, 401) - eq_(cm.exception.errno, 109) + assert cm.value.status_code == 401 + assert cm.value.errno == 109 diff --git a/autopush/tests/test_web_webpush.py b/autopush/tests/test_web_webpush.py index c5ff0873..ac01a3cb 100644 --- a/autopush/tests/test_web_webpush.py +++ b/autopush/tests/test_web_webpush.py @@ -3,7 +3,6 @@ from cryptography.fernet import Fernet from mock import Mock -from nose.tools import eq_, ok_ from twisted.internet.defer import inlineCallbacks from twisted.trial import unittest @@ -63,10 +62,10 @@ def test_router_needs_update(self): resp = yield self.client.post( self.url(api_ver="v1", token=dummy_token), ) - eq_(resp.get_status(), 503) + assert resp.get_status() == 503 ru = self.db.router.register_user - ok_(ru.called) - eq_('webpush', ru.call_args[0][0].get('router_type')) + assert ru.called + assert 'webpush' == ru.call_args[0][0].get('router_type') @inlineCallbacks def test_router_returns_data_without_detail(self): @@ -90,8 +89,8 @@ def test_router_returns_data_without_detail(self): resp = yield self.client.post( self.url(api_ver="v1", token=dummy_token), ) - eq_(resp.get_status(), 503) - ok_(self.db.router.drop_user.called) + assert resp.get_status() == 503 + assert self.db.router.drop_user.called @inlineCallbacks def test_request_bad_ckey(self): @@ -100,7 +99,7 @@ def test_request_bad_ckey(self): self.url(api_ver="v1", token='ignored'), headers={'crypto-key': 'dummy_key'} ) - eq_(resp.get_status(), 404) + assert resp.get_status() == 404 @inlineCallbacks def test_request_bad_v1_id(self): @@ -108,7 +107,7 @@ def test_request_bad_v1_id(self): resp = yield self.client.post( self.url(api_ver="v1", token='ignored'), ) - eq_(resp.get_status(), 404) + assert resp.get_status() == 404 @inlineCallbacks def test_request_bad_v2_id_short(self): @@ -117,7 +116,7 @@ def test_request_bad_v2_id_short(self): self.url(api_ver='v2', token='ignored'), headers={'authorization': 'vapid t=dummy_key,k=aaa'} ) - eq_(resp.get_status(), 404) + assert resp.get_status() == 404 @inlineCallbacks def test_request_bad_draft02_auth(self): @@ -125,7 +124,7 @@ def test_request_bad_draft02_auth(self): self.url(api_ver='v2', token='ignored'), headers={'authorization': 'vapid foo'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_bad_draft02_missing_key(self): @@ -134,7 +133,7 @@ def test_request_bad_draft02_missing_key(self): self.url(api_ver='v2', token='ignored'), headers={'authorization': 'vapid t=dummy.key.value,k='} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_bad_draft02_bad_pubkey(self): @@ -143,7 +142,7 @@ def test_request_bad_draft02_bad_pubkey(self): self.url(api_ver='v2', token='ignored'), headers={'authorization': 'vapid t=dummy.key.value,k=!aaa'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_bad_v2_id_missing_pubkey(self): @@ -153,7 +152,7 @@ def test_request_bad_v2_id_missing_pubkey(self): headers={'crypto-key': 'key_id=dummy_key', 'authorization': 'dummy_key'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_v2_id_variant_pubkey(self): @@ -170,7 +169,7 @@ def test_request_v2_id_variant_pubkey(self): headers={'crypto-key': 'p256ecdsa=' + variant_key, 'authorization': 'webpush dummy.key'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_v2_id_no_crypt_auth(self): @@ -185,7 +184,7 @@ def test_request_v2_id_no_crypt_auth(self): self.url(api_ver='v1', token='ignored'), headers={'authorization': 'webpush dummy.key'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 @inlineCallbacks def test_request_bad_v2_id_bad_pubkey(self): @@ -195,4 +194,4 @@ def test_request_bad_v2_id_bad_pubkey(self): headers={'crypto-key': 'p256ecdsa=Invalid!', 'authorization': 'dummy_key'} ) - eq_(resp.get_status(), 401) + assert resp.get_status() == 401 diff --git a/autopush/tests/test_webpush_server.py b/autopush/tests/test_webpush_server.py index fb238a85..324bb3fe 100644 --- a/autopush/tests/test_webpush_server.py +++ b/autopush/tests/test_webpush_server.py @@ -9,8 +9,8 @@ from boto.dynamodb2.exceptions import ItemNotFound from boto.dynamodb2.exceptions import ProvisionedThroughputExceededException from mock import Mock -from nose.tools import assert_raises, ok_, eq_ from twisted.logger import globalLogPublisher +import pytest from autopush.db import ( DatabaseManager, @@ -203,7 +203,7 @@ def test_start_stop(self): ws = self._makeFUT() ws.start() try: - eq_(len(ws.workers), 2) + assert len(ws.workers) == 2 finally: ws.stop() @@ -217,8 +217,8 @@ def test_hello_process(self): uaid=hello.uaid.hex, connected_at=hello.connected_at, )) - ok_("error" not in result) - ok_(hello.uaid.hex != result["uaid"]) + assert "error" not in result + assert hello.uaid.hex != result["uaid"] finally: ws.stop() @@ -232,20 +232,20 @@ def test_nonexisting_uaid(self): p = self._makeFUT() hello = HelloFactory() result = p.process(hello) # type: HelloResponse - ok_(isinstance(result, HelloResponse)) - ok_(hello.uaid != result.uaid) - eq_(result.check_storage, False) + assert isinstance(result, HelloResponse) + assert hello.uaid != result.uaid + assert result.check_storage is False def test_existing_uaid(self): p = self._makeFUT() hello = HelloFactory() success, _ = self.db.router.register_user(UserItemFactory( uaid=hello.uaid.hex)) - eq_(success, True) + assert success is True result = p.process(hello) # type: HelloResponse - ok_(isinstance(result, HelloResponse)) - eq_(hello.uaid.hex, result.uaid) - eq_(result.check_storage, True) + assert isinstance(result, HelloResponse) + assert hello.uaid.hex == result.uaid + assert result.check_storage is True def test_existing_newer_uaid(self): p = self._makeFUT() @@ -255,8 +255,8 @@ def test_existing_newer_uaid(self): connected_at=hello.connected_at+10) ) result = p.process(hello) # type: HelloResponse - ok_(isinstance(result, HelloResponse)) - eq_(result.uaid, None) + assert isinstance(result, HelloResponse) + assert result.uaid is None class TestCheckStorageProcessor(BaseSetup): @@ -268,14 +268,14 @@ def test_no_messages(self): p = self._makeFUT() check = CheckStorageFactory(message_month=self.db.current_msg_month) result = p.process(check) - eq_(len(result.messages), 0) + assert len(result.messages) == 0 def test_five_messages(self): p = self._makeFUT() check = CheckStorageFactory(message_month=self.db.current_msg_month) self._store_messages(check.uaid, num=5) result = p.process(check) - eq_(len(result.messages), 5) + assert len(result.messages) == 5 def test_many_messages(self): """Test many messages to fill the batches with topics and non-topic @@ -290,7 +290,7 @@ def test_many_messages(self): self._store_messages(check.uaid, topic=True, num=22) self._store_messages(check.uaid, num=15) result = p.process(check) - eq_(len(result.messages), 10) + assert len(result.messages) == 10 # Delete all the messages returned for msg in result.messages: @@ -300,7 +300,7 @@ def test_many_messages(self): check.timestamp = result.timestamp check.include_topic = result.include_topic result = p.process(check) - eq_(len(result.messages), 10) + assert len(result.messages) == 10 # Delete all the messages returned for msg in result.messages: @@ -310,7 +310,7 @@ def test_many_messages(self): check.timestamp = result.timestamp check.include_topic = result.include_topic result = p.process(check) - eq_(len(result.messages), 2) + assert len(result.messages) == 2 # Delete all the messages returned for msg in result.messages: @@ -320,12 +320,12 @@ def test_many_messages(self): check.timestamp = result.timestamp check.include_topic = result.include_topic result = p.process(check) - eq_(len(result.messages), 10) + assert len(result.messages) == 10 check.timestamp = result.timestamp check.include_topic = result.include_topic result = p.process(check) - eq_(len(result.messages), 5) + assert len(result.messages) == 5 class TestIncrementStorageProcessor(BaseSetup): @@ -345,7 +345,7 @@ def test_inc_storage(self): # Pull 10 out check_result = check_command.process(check) - eq_(len(check_result.messages), 10) + assert len(check_result.messages) == 10 # We should now have an updated timestamp returned, increment it inc = IncStoragePosition(uaid=uaid.hex, @@ -359,7 +359,7 @@ def test_inc_storage(self): message_month=self.db.current_msg_month ) check_result = check_command.process(check) - eq_(len(check_result.messages), 5) + assert len(check_result.messages) == 5 class TestDeleteMessageProcessor(BaseSetup): @@ -378,7 +378,7 @@ def test_delete_message(self): # Fetch them results = check_command.process(check) - eq_(len(results.messages), 7) + assert len(results.messages) == 7 # Delete 2 of them for notif in results.messages[:2]: @@ -389,7 +389,7 @@ def test_delete_message(self): # Fetch messages again results = check_command.process(check) - eq_(len(results.messages), 5) + assert len(results.messages) == 5 class TestDropUserProcessor(BaseSetup): @@ -407,13 +407,13 @@ def test_drop_user(self): # Check that its there item = self.db.router.get_uaid(uaid) - ok_(item is not None) + assert item is not None # Drop it drop_command.process(DropUser(uaid=uaid)) # Verify its gone - with assert_raises(ItemNotFound): + with pytest.raises(ItemNotFound): self.db.router.get_uaid(uaid) @@ -437,9 +437,9 @@ def test_migrate_user(self): # Check that it's there item = self.db.router.get_uaid(uaid) _, channels = self.db.message_tables[last_month].all_channels(uaid) - ok_(item["current_month"] != self.db.current_msg_month) - ok_(item is not None) - eq_(len(channels), 3) + assert item["current_month"] != self.db.current_msg_month + assert item is not None + assert len(channels) == 3 # Migrate it migrate_command.process( @@ -449,9 +449,9 @@ def test_migrate_user(self): # Check that it's in the new spot item = self.db.router.get_uaid(uaid) _, channels = self.db.message.all_channels(uaid) - eq_(item["current_month"], self.db.current_msg_month) - ok_(item is not None) - eq_(len(channels), 3) + assert item["current_month"] == self.db.current_msg_month + assert item is not None + assert len(channels) == 3 class TestRegisterProcessor(BaseSetup): @@ -468,14 +468,14 @@ def test_register(self): channel_id=chid, message_month=self.db.current_msg_month) ) - ok_(result.endpoint) - ok_(self.metrics.increment.called) - eq_(self.metrics.increment.call_args[0][0], 'ua.command.register') - ok_(self.logs.logged( + assert result.endpoint + assert self.metrics.increment.called + assert self.metrics.increment.call_args[0][0] == 'ua.command.register' + assert self.logs.logged( lambda e: (e['log_format'] == "Register" and e['channel_id'] == chid and e['endpoint'] == result.endpoint) - )) + ) def _test_invalid(self, chid, msg="use lower case, dashed format", status=401): @@ -485,9 +485,9 @@ def _test_invalid(self, chid, msg="use lower case, dashed format", channel_id=chid, message_month=self.db.current_msg_month) ) - ok_(result.error) - ok_(msg in result.error_msg) - eq_(status, result.status) + assert result.error + assert msg in result.error_msg + assert status == result.status def test_register_bad_chid(self): self._test_invalid("oof", "Invalid UUID") @@ -518,13 +518,14 @@ def test_unregister(self): channel_id=chid, message_month=self.db.current_msg_month) ) - ok_(result.success) - ok_(self.metrics.increment.called) - eq_(self.metrics.increment.call_args[0][0], 'ua.command.unregister') - ok_(self.logs.logged( + assert result.success + assert self.metrics.increment.called + assert self.metrics.increment.call_args[0][0] == \ + 'ua.command.unregister' + assert self.logs.logged( lambda e: (e['log_format'] == "Unregister" and e['channel_id'] == chid) - )) + ) def test_unregister_bad_chid(self): cmd = self._makeFUT() @@ -533,8 +534,8 @@ def test_unregister_bad_chid(self): channel_id="quux", message_month=self.db.current_msg_month) ) - ok_(result.error) - ok_("Invalid UUID" in result.error_msg) + assert result.error + assert "Invalid UUID" in result.error_msg class TestStoreMessagesProcessor(BaseSetup): @@ -546,4 +547,4 @@ def test_store_messages(self): cmd = self._makeFUT() store_message = StoreMessageFactory() response = cmd.process(store_message) - eq_(response.success, True) + assert response.success is True diff --git a/autopush/tests/test_websocket.py b/autopush/tests/test_websocket.py index 840e7951..85681e35 100644 --- a/autopush/tests/test_websocket.py +++ b/autopush/tests/test_websocket.py @@ -13,7 +13,7 @@ ) from boto.exception import JSONResponseError from mock import Mock, patch -from nose.tools import assert_raises, eq_, ok_ +import pytest from twisted.internet import reactor from twisted.internet.defer import ( inlineCallbacks, @@ -191,8 +191,8 @@ def test_autoping_no_uaid(self, mock_reactor): self.proto.sendClose = self.orig_close self._connect() self.proto._sendAutoPing() - ok_(mock_reactor.callLater.called) - ok_(WebSocketServerProtocol.sendClose.called) + assert mock_reactor.callLater.called + assert WebSocketServerProtocol.sendClose.called @patch("autopush.websocket.reactor") def test_autoping_uaid_not_in_clients(self, mock_reactor): @@ -203,8 +203,8 @@ def test_autoping_uaid_not_in_clients(self, mock_reactor): self._connect() self.proto.ps.uaid = uuid.uuid4().hex self.proto._sendAutoPing() - ok_(mock_reactor.callLater.called) - ok_(WebSocketServerProtocol.sendClose.called) + assert mock_reactor.callLater.called + assert WebSocketServerProtocol.sendClose.called @patch("autopush.websocket.reactor") def test_nuke_connection(self, mock_reactor): @@ -221,25 +221,25 @@ def test_nuke_connection_shutdown_ran(self, mock_reactor): self.proto.ps.uaid = uuid.uuid4().hex self.proto._shutdown_ran = True self.proto.nukeConnection() - eq_(len(mock_reactor.mock_calls), 0) + assert len(mock_reactor.mock_calls) == 0 def test_producer_interface(self): self._connect() self.proto.ps.pauseProducing() - eq_(self.proto.paused, True) + assert self.proto.paused is True self.proto.ps.resumeProducing() - eq_(self.proto.paused, False) - eq_(self.proto.ps._should_stop, False) + assert self.proto.paused is False + assert self.proto.ps._should_stop is False self.proto.ps.stopProducing() - eq_(self.proto.paused, True) - eq_(self.proto.ps._should_stop, True) + assert self.proto.paused is True + assert self.proto.ps._should_stop is True def test_headers_locate(self): req = ConnectionRequest("localhost", {"user-agent": "Me"}, "localhost", "/", {}, 1, "localhost", [], []) self.proto.onConnect(req) - eq_(self.proto.ps._user_agent, "Me") + assert self.proto.ps._user_agent == "Me" def test_base_tags(self): req = Mock() @@ -249,34 +249,34 @@ def test_base_tags(self): "CLR 3.5.30729)"} req.host = "example.com:8080" ps = PushState.from_request(request=req, db=self.proto.db) - eq_(sorted(ps._base_tags), - sorted(['ua_os_family:Windows', - 'ua_browser_family:Firefox', - 'host:example.com:8080'])) + assert sorted(ps._base_tags) == sorted( + ['ua_os_family:Windows', + 'ua_browser_family:Firefox', + 'host:example.com:8080']) def test_handshake_sub(self): self.factory.externalPort = 80 def check_subbed(s): - eq_(self.factory.externalPort, None) + assert self.factory.externalPort is None return False self.proto.parent_class = Mock(**{"processHandshake.side_effect": check_subbed}) self.proto.processHandshake() - eq_(self.factory.externalPort, 80) + assert self.factory.externalPort == 80 def test_handshake_nosub(self): self.conf.port = self.factory.externalPort = 80 def check_subbed(s): - eq_(self.factory.externalPort, 80) + assert self.factory.externalPort == 80 return False self.proto.parent_class = Mock(**{"processHandshake.side_effect": check_subbed}) self.proto.processHandshake() - eq_(self.factory.externalPort, 80) + assert self.factory.externalPort == 80 def test_handshake_decode_error(self): self.proto.factory = Mock(externalPort=80) @@ -302,7 +302,7 @@ def check_subbed(s): self.proto.parent_class = Mock(**{"processHandshake.side_effect": check_subbed}) - with assert_raises(ValueError): + with pytest.raises(ValueError): self.proto.processHandshake() self.proto._log_exc = True @@ -331,7 +331,7 @@ def test_no_messagetype_after_hello(self): self._send_message(dict(data="wassup")) close_args = yield self._wait_for_close() _, kwargs = close_args - eq_(len(kwargs), 0) + assert len(kwargs) == 0 @inlineCallbacks def test_unknown_messagetype(self): @@ -340,7 +340,7 @@ def test_unknown_messagetype(self): self._send_message(dict(messageType="wassup")) close_args = yield self._wait_for_close() _, kwargs = close_args - eq_(len(kwargs), 0) + assert len(kwargs) == 0 def test_close_with_cleanup(self): self._connect() @@ -351,10 +351,10 @@ def test_close_with_cleanup(self): notif_mock = Mock() self.proto.ps._callbacks.append(notif_mock) self.proto.onClose(True, None, None) - eq_(len(self.factory.clients), 0) - eq_(len(list(notif_mock.mock_calls)), 1) + assert len(self.factory.clients) == 0 + assert len(list(notif_mock.mock_calls)) == 1 name, _, _ = notif_mock.mock_calls[0] - eq_(name, "cancel") + assert name == "cancel" @inlineCallbacks def test_close_with_cleanup_no_node(self): @@ -370,7 +370,7 @@ def test_close_with_cleanup_no_node(self): mock_get.return_value = dict(foo="bar") self.proto.onClose(True, None, None) yield sleep(.25) - eq_(len(self.factory.clients), 0) + assert len(self.factory.clients) == 0 @inlineCallbacks def test_close_with_delivery_cleanup(self): @@ -432,7 +432,7 @@ def test_close_with_delivery_cleanup_and_get_no_result(self): # Close the connection self.proto.onClose(True, None, None) yield self._wait_for(lambda: len(self.metrics.mock_calls) > 0) - eq_(self.metrics.timing.call_args[0][0], 'ua.connection.lifespan') + assert self.metrics.timing.call_args[0][0] == 'ua.connection.lifespan' # Wait for final cleanup (no error or metric produced) yield sleep(.25) @@ -490,12 +490,12 @@ def fake_msg(data): use_webpush=True)) msg = yield self.get_response() - eq_(self.proto.ps.rotate_message_table, False) + assert self.proto.ps.rotate_message_table is False # it's fine you've not connected in a while, but you should # recycle your endpoints since they're probably invalid by now # anyway. - eq_(msg["status"], 200) - ok_(msg["uaid"] != orig_uaid) + assert msg["status"] == 200 + assert msg["uaid"] != orig_uaid @inlineCallbacks def test_hello_tomorrow(self): @@ -549,12 +549,12 @@ def fake_msg(data): # it's fine you've not connected in a while, but you should # recycle your endpoints since they're probably invalid by now # anyway. - eq_(msg["status"], 200) - eq_(msg["uaid"], orig_uaid) + assert msg["status"] == 200 + assert msg["uaid"] == orig_uaid # Wait to see that the message table gets rotated yield self._wait_for(lambda: not self.proto.ps.rotate_message_table) - eq_(self.proto.ps.rotate_message_table, False) + assert self.proto.ps.rotate_message_table is False @inlineCallbacks def test_hello_tomorrow_provision_error(self): @@ -621,14 +621,14 @@ def raise_error(*args): # it's fine you've not connected in a while, but # you should recycle your endpoints since they're probably # invalid by now anyway. - eq_(msg["status"], 200) - eq_(msg["uaid"], orig_uaid) + assert msg["status"] == 200 + assert msg["uaid"] == orig_uaid # Wait to see that the message table gets rotated yield self._wait_for( lambda: not self.proto.ps.rotate_message_table ) - eq_(self.proto.ps.rotate_message_table, False) + assert self.proto.ps.rotate_message_table is False finally: patch_range.stop() @@ -641,9 +641,9 @@ def test_hello_webpush_uses_one_db_call(self): channelIDs=[])) msg = yield self.get_response() yield self._wait_for(lambda: len(db.DB_CALLS) > 2, duration=3) - eq_(db.DB_CALLS, - ['register_user', 'fetch_messages', 'fetch_timestamp_messages']) - eq_(msg["status"], 200) + assert db.DB_CALLS == [ + 'register_user', 'fetch_messages', 'fetch_timestamp_messages'] + assert msg["status"] == 200 db.DB_CALLS = [] db.TRACK_DB_CALLS = False @@ -652,10 +652,10 @@ def test_hello_with_webpush(self): self._connect() self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) - eq_(self.proto.base_tags, ['use_webpush:True']) + assert self.proto.base_tags == ['use_webpush:True'] msg = yield self.get_response() - eq_(msg["status"], 200) - ok_("use_webpush" in msg) + assert msg["status"] == 200 + assert "use_webpush" in msg @inlineCallbacks def test_hello_with_missing_current_month(self): @@ -670,8 +670,8 @@ def test_hello_with_missing_current_month(self): self._send_message(dict(messageType="hello", channelIDs=[], uaid=uaid, use_webpush=True)) msg = yield self.get_response() - eq_(msg["status"], 200) - ok_(msg["uaid"] != uaid) + assert msg["status"] == 200 + assert msg["uaid"] != uaid @inlineCallbacks def test_hello_with_bad_uaid(self): @@ -680,8 +680,8 @@ def test_hello_with_bad_uaid(self): self._send_message(dict(messageType="hello", channelIDs=[], use_webpush=True, uaid=uaid)) msg = yield self.get_response() - eq_(msg["status"], 200) - ok_(msg["uaid"] != uaid) + assert msg["status"] == 200 + assert msg["uaid"] != uaid @inlineCallbacks def test_hello_with_bad_uaid_dash(self): @@ -690,8 +690,8 @@ def test_hello_with_bad_uaid_dash(self): self._send_message(dict(messageType="hello", channelIDs=[], use_webpush=True, uaid=uaid)) msg = yield self.get_response() - eq_(msg["status"], 200) - ok_(msg["uaid"] != uaid) + assert msg["status"] == 200 + assert msg["uaid"] != uaid @inlineCallbacks def test_hello_with_bad_uaid_case(self): @@ -700,8 +700,8 @@ def test_hello_with_bad_uaid_case(self): self._send_message(dict(messageType="hello", channelIDs=[], use_webpush=True, uaid=uaid)) msg = yield self.get_response() - eq_(msg["status"], 200) - ok_(msg["uaid"] != uaid) + assert msg["status"] == 200 + assert msg["uaid"] != uaid @inlineCallbacks def test_hello_failure(self): @@ -713,8 +713,8 @@ def test_hello_failure(self): self._send_message(dict(messageType="hello", channelIDs=[], use_webpush=True, stop=1)) msg = yield self.get_response() - eq_(msg["status"], 503) - eq_(msg["reason"], "error") + assert msg["status"] == 503 + assert msg["reason"] == "error" self.flushLoggedErrors() @inlineCallbacks @@ -732,8 +732,8 @@ def throw_error(*args, **kwargs): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 503) - eq_(msg["reason"], "error - overloaded") + assert msg["status"] == 503 + assert msg["reason"] == "error - overloaded" self.flushLoggedErrors() @inlineCallbacks @@ -752,8 +752,8 @@ def throw_error(*args, **kwargs): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 503) - eq_(msg["reason"], "error - overloaded") + assert msg["status"] == 503 + assert msg["reason"] == "error - overloaded" self.flushLoggedErrors() @inlineCallbacks @@ -768,9 +768,9 @@ def test_hello_check_fail(self): channelIDs=[])) msg = yield self.get_response() calls = self.proto.db.router.register_user.mock_calls - eq_(len(calls), 1) - eq_(msg["status"], 500) - eq_(msg["reason"], "already_connected") + assert len(calls) == 1 + assert msg["status"] == 500 + assert msg["reason"] == "already_connected" @inlineCallbacks def test_hello_dupe(self): @@ -778,13 +778,13 @@ def test_hello_dupe(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 200) + assert msg["status"] == 200 # Send another hello self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 401) + assert msg["status"] == 401 @inlineCallbacks def test_hello_timeout(self): @@ -793,8 +793,8 @@ def test_hello_timeout(self): self._connect() close_args = yield self._wait_for_close() _, kwargs = close_args - eq_(len(kwargs), 0) - ok_(time.time() - connected >= 3) + assert len(kwargs) == 0 + assert time.time() - connected >= 3 @inlineCallbacks def test_not_hello(self): @@ -802,7 +802,7 @@ def test_not_hello(self): self._send_message(dict(messageType="wooooo")) close_args = yield self._wait_for_close() _, kwargs = close_args - eq_(len(kwargs), 0) + assert len(kwargs) == 0 @inlineCallbacks def test_hello_env(self): @@ -810,7 +810,7 @@ def test_hello_env(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["env"], "test") + assert msg["env"] == "test" @inlineCallbacks def test_ping(self): @@ -818,10 +818,10 @@ def test_ping(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 200) + assert msg["status"] == 200 self._send_message({}) msg = yield self.get_response() - eq_(msg, {}) + assert msg == {} @inlineCallbacks def test_ping_too_much(self): @@ -829,18 +829,18 @@ def test_ping_too_much(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["status"], 200) + assert msg["status"] == 200 self.proto.ps.last_ping = time.time() - 30 self.proto.sendClose = Mock() self._send_message({}) - ok_(self.proto.sendClose.called) + assert self.proto.sendClose.called def test_auto_ping(self): self.proto.ps.ping_time_out = False self.proto.dropConnection = Mock() self.proto.onAutoPingTimeout() - ok_(self.proto.ps.ping_time_out, True) - ok_(self.proto.dropConnection.called) + assert self.proto.ps.ping_time_out is True + assert self.proto.dropConnection.called def test_defer_to_later(self): self._connect() @@ -849,7 +849,7 @@ def fail(): raise twisted.internet.defer.CancelledError def fail2(failure): - ok_(failure) + assert failure def check_result(result): # pragma: nocover pass @@ -857,7 +857,7 @@ def check_result(result): # pragma: nocover d = self.proto.deferToLater(0, fail) d.addCallback(check_result) d.addErrback(fail2) - ok_(d is not None) + assert d is not None def test_defer_to_later_cancel(self): self._connect() @@ -895,12 +895,12 @@ def __call__(self): return True def check_result(result): - eq_(result, True) + assert result is True self.flushLoggedErrors() d = self.proto.force_retry(Fail()) d.addCallback(check_result) - ok_(d is not None) + assert d is not None return d @inlineCallbacks @@ -909,14 +909,14 @@ def test_register(self): self._send_message(dict(messageType="hello", channelIDs=[], use_webpush=True, stop=1)) msg = yield self.get_response() - ok_("messageType" in msg) + assert "messageType" in msg self._send_message(dict(messageType="register", channelID=str(uuid.uuid4()))) msg = yield self.get_response() - eq_(msg["status"], 200) - eq_(msg["messageType"], "register") - ok_("pushEndpoint" in msg) + assert msg["status"] == 200 + assert msg["messageType"] == "register" + assert "pushEndpoint" in msg assert_called_included(self.proto.log.info, format="Register") @inlineCallbacks @@ -927,7 +927,7 @@ def test_register_webpush(self): self.proto.db.message.register_channel = Mock() yield self.proto.process_register(dict(channelID=chid)) - ok_(self.proto.db.message.register_channel.called) + assert self.proto.db.message.register_channel.called assert_called_included(self.proto.log.info, format="Register") @inlineCallbacks @@ -953,9 +953,9 @@ def echo(string): dict(channelID=chid, key=base64url_encode(test_key)) ) - eq_(test_endpoint, - self.proto.sendJSON.call_args[0][0]['pushEndpoint']) - ok_(self.proto.db.message.register_channel.called) + assert test_endpoint == self.proto.sendJSON.call_args[0][0][ + 'pushEndpoint'] + assert self.proto.db.message.register_channel.called assert_called_included(self.proto.log.info, format="Register") @inlineCallbacks @@ -964,12 +964,12 @@ def test_register_no_chid(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - ok_("messageType" in msg) + assert "messageType" in msg self._send_message(dict(messageType="register")) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "register") + assert msg["status"] == 401 + assert msg["messageType"] == "register" @inlineCallbacks def test_register_bad_chid(self): @@ -977,12 +977,12 @@ def test_register_bad_chid(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - ok_("messageType" in msg) + assert "messageType" in msg self._send_message(dict(messageType="register", channelID="oof")) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "register") + assert msg["status"] == 401 + assert msg["messageType"] == "register" @inlineCallbacks def test_register_bad_chid_upper(self): @@ -990,13 +990,13 @@ def test_register_bad_chid_upper(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - ok_("messageType" in msg) + assert "messageType" in msg self._send_message(dict(messageType="register", channelID=str(uuid.uuid4()).upper())) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "register") + assert msg["status"] == 401 + assert msg["messageType"] == "register" @inlineCallbacks def test_register_bad_chid_nodash(self): @@ -1004,13 +1004,13 @@ def test_register_bad_chid_nodash(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - ok_("messageType" in msg) + assert "messageType" in msg self._send_message(dict(messageType="register", channelID=str(uuid.uuid4()).replace('-', ''))) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "register") + assert msg["status"] == 401 + assert msg["messageType"] == "register" @inlineCallbacks def test_register_bad_crypto(self): @@ -1024,8 +1024,8 @@ def throw_error(*args, **kwargs): self._send_message(dict(messageType="register", channelID=str(uuid.uuid4()))) msg = yield self.get_response() - eq_(msg["status"], 500) - eq_(msg["messageType"], "register") + assert msg["status"] == 500 + assert msg["messageType"] == "register" self.proto.log.failure.assert_called() def test_register_kill_others(self): @@ -1067,12 +1067,12 @@ def throw_provisioned(*args, **kwargs): register.side_effect = throw_provisioned yield self.proto.process_register(dict(channelID=chid)) - ok_(self.proto.db.message.register_channel.called) - ok_(self.send_mock.called) + assert self.proto.db.message.register_channel.called + assert self.send_mock.called args, _ = self.send_mock.call_args msg = json.loads(args[0]) - eq_(msg["messageType"], "error") - eq_(msg["reason"], "overloaded") + assert msg["messageType"] == "error" + assert msg["reason"] == "overloaded" def test_check_kill_self(self): self._connect() @@ -1090,8 +1090,8 @@ def test_check_kill_self(self): res = dict(node_id=node_id, connected_at=connected, uaid=uaid) self.proto._check_other_nodes((True, res)) # the current one should be dropped. - eq_(ff.sendClose.call_count, 0) - eq_(self.proto.sendClose.call_count, 1) + assert ff.sendClose.call_count == 0 + assert self.proto.sendClose.call_count == 1 def test_check_kill_existing(self): self._connect() @@ -1108,15 +1108,15 @@ def test_check_kill_existing(self): res = dict(node_id=node_id, connected_at=connected, uaid=uaid) self.proto._check_other_nodes((True, res)) # the existing one should be dropped. - eq_(ff.sendClose.call_count, 1) - eq_(self.proto.sendClose.call_count, 0) + assert ff.sendClose.call_count == 1 + assert self.proto.sendClose.call_count == 0 def test_unregister_with_webpush(self): chid = str(uuid.uuid4()) self._connect() self.proto.force_retry = Mock() self.proto.process_unregister(dict(channelID=chid)) - ok_(self.proto.force_retry.called) + assert self.proto.force_retry.called @inlineCallbacks def test_ws_unregister(self): @@ -1125,16 +1125,16 @@ def test_ws_unregister(self): self._send_message(dict(messageType="hello", use_webpush=True, channelIDs=[])) msg = yield self.get_response() - eq_(msg["messageType"], "hello") - eq_(msg["status"], 200) + assert msg["messageType"] == "hello" + assert msg["status"] == 200 self._send_message(dict(messageType="unregister", code=104, channelID=chid)) msg = yield self.get_response() - eq_(msg["status"], 200) - eq_(msg["channelID"], chid) - eq_(len(self.proto.log.mock_calls), 2) + assert msg["status"] == 200 + assert msg["channelID"] == chid + assert len(self.proto.log.mock_calls) == 2 assert_called_included(self.proto.log.info, format="Unregister") @inlineCallbacks @@ -1143,8 +1143,8 @@ def test_ws_unregister_without_chid(self): self.proto.ps.uaid = uuid.uuid4().hex self._send_message(dict(messageType="unregister")) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "unregister") + assert msg["status"] == 401 + assert msg["messageType"] == "unregister" @inlineCallbacks def test_ws_unregister_bad_chid(self): @@ -1153,8 +1153,8 @@ def test_ws_unregister_bad_chid(self): self._send_message(dict(messageType="unregister", channelID="}{$@!asdf")) msg = yield self.get_response() - eq_(msg["status"], 401) - eq_(msg["messageType"], "unregister") + assert msg["status"] == 401 + assert msg["messageType"] == "unregister" def test_notification_with_webpush(self): self._connect() @@ -1178,11 +1178,12 @@ def test_notification_with_webpush(self): # Check the call result args = json.loads(self.send_mock.call_args[0][0]) - eq_(args, {"messageType": "notification", - "channelID": chid, - "data": dummy_data, - "version": "10", - "headers": fixed_headers}) + assert args == { + "messageType": "notification", + "channelID": chid, + "data": dummy_data, + "version": "10", + "headers": fixed_headers} @inlineCallbacks def test_hello_not_webpush(self): @@ -1190,8 +1191,8 @@ def test_hello_not_webpush(self): self._send_message(dict(messageType="hello", channelIDs=[])) msg = yield self.get_response() - eq_(msg['status'], 401) - ok_('Simplepush not supported' in msg['reason']) + assert msg['status'] == 401 + assert 'Simplepush not supported' in msg['reason'] @inlineCallbacks def test_ack(self): @@ -1204,7 +1205,7 @@ def test_ack(self): notif = make_webpush_notification(self.proto.ps.uaid, chid) self.proto.ps.direct_updates[chid] = [notif] msg = yield self.get_response() - eq_(msg["status"], 200) + assert msg["status"] == 200 # Send our ack self._send_message(dict(messageType="ack", @@ -1212,8 +1213,9 @@ def test_ack(self): "version": notif.version}])) # Verify it was cleared out - eq_(len(self.proto.ps.direct_updates.get(str(notif.channel_id))), 0) - eq_(len(self.proto.log.debug.mock_calls), 2) + assert len(self.proto.ps.direct_updates.get( + str(notif.channel_id))) == 0 + assert len(self.proto.log.debug.mock_calls) == 2 assert_called_included(self.proto.log.debug, format="Ack", router_key="webpush", @@ -1222,7 +1224,7 @@ def test_ack(self): def test_ack_with_bad_input(self): self._connect() - eq_(self.proto.ack_update(None), None) + assert self.proto.ack_update(None) is None def test_ack_with_webpush_from_storage(self): self._connect() @@ -1240,9 +1242,9 @@ def test_ack_with_webpush_from_storage(self): version=dummy_version, code=200 )) - ok_(self.proto.force_retry.called) - ok_(mock_defer.addBoth.called) - eq_(len(self.proto.log.debug.mock_calls), 1) + assert self.proto.force_retry.called + assert mock_defer.addBoth.called + assert len(self.proto.log.debug.mock_calls) == 1 assert_called_included(self.proto.log.debug, format="Ack", router_key="webpush", @@ -1256,7 +1258,7 @@ def test_nack(self): version=dummy_version, code=200 )), False) - eq_(len(self.proto.log.debug.mock_calls), 1) + assert len(self.proto.log.debug.mock_calls) == 1 def test_nack_no_version(self): self._connect() @@ -1265,14 +1267,14 @@ def test_nack_no_version(self): messageType="nack", code=200 )), False) - eq_(len(self.proto.log.debug.mock_calls), 0) + assert len(self.proto.log.debug.mock_calls) == 0 def test_ack_remove(self): self._connect() notif = dummy_notif() self.proto.ps.updates_sent[dummy_chid_str] = [notif] self.proto._handle_webpush_update_remove(None, dummy_chid_str, notif) - eq_(self.proto.ps.updates_sent[dummy_chid_str], []) + assert self.proto.ps.updates_sent[dummy_chid_str] == [] def test_ack_remove_not_set(self): self._connect() @@ -1294,7 +1296,7 @@ def test_ack_missing_updates(self): self._send_message(dict(messageType="ack")) calls = self.proto.sendJSON.call_args_list - eq_(len(calls), 0) + assert len(calls) == 0 def test_ack_missing_chid_version(self): self._connect() @@ -1304,7 +1306,7 @@ def test_ack_missing_chid_version(self): updates=[{"something": 2}])) calls = self.send_mock.call_args_list - eq_(len(calls), 0) + assert len(calls) == 0 def test_process_notifications(self): twisted.internet.base.DelayedCall.debug = True @@ -1331,7 +1333,7 @@ def test_process_notifications(self): notif_d.addErrback(lambda x: d.errback(x)) def wait(result): - eq_(self.proto.ps._notification_fetch, None) + assert self.proto.ps._notification_fetch is None d.callback(True) self.proto.ps._notification_fetch.addCallback(wait) self.proto.ps._notification_fetch.addErrback(lambda x: d.errback(x)) @@ -1363,8 +1365,8 @@ def throw(*args, **kwargs): def wait(result): fail = self.proto.log.failure - ok_(fail.called) - eq_(fail.call_args[1].get('failure').value[0], 'Krikey') + assert fail.called + assert fail.call_args[1].get('failure').value[0] == 'Krikey' d.callback(True) self.proto.ps._notification_fetch.addCallback(wait) @@ -1400,7 +1402,7 @@ def throw(*args, **kwargs): notif_d.addErrback(lambda x: d.errback(x)) def wait(result): - ok_(self.proto.deferToLater.called) + assert self.proto.deferToLater.called d.callback(True) self.proto.ps._notification_fetch.addCallback(wait) @@ -1413,8 +1415,8 @@ def test_process_notif_doesnt_run_with_webpush_outstanding(self): self.proto.ps.updates_sent[dummy_chid_str] = [dummy_notif()] self.proto.deferToLater = Mock() self.proto.process_notifications() - ok_(self.proto.deferToLater.called) - eq_(self.proto.ps._notification_fetch, None) + assert self.proto.deferToLater.called + assert self.proto.ps._notification_fetch is None def test_process_notif_doesnt_run_when_paused(self): self._connect() @@ -1422,21 +1424,21 @@ def test_process_notif_doesnt_run_when_paused(self): self.proto.ps.pauseProducing() with patch("autopush.websocket.reactor") as mr: self.proto.process_notifications() - ok_(mr.callLater.mock_calls > 0) + assert mr.callLater.mock_calls > 0 def test_process_notif_doesnt_run_after_stop(self): self._connect() self.proto.ps.uaid = uuid.uuid4().hex self.proto.ps._should_stop = True self.proto.process_notifications() - eq_(self.proto.ps._notification_fetch, None) + assert self.proto.ps._notification_fetch is None def test_check_notif_doesnt_run_after_stop(self): self._connect() self.proto.ps.uaid = uuid.uuid4().hex self.proto.ps._should_stop = True self.proto.check_missed_notifications(None) - eq_(self.proto.ps._notification_fetch, None) + assert self.proto.ps._notification_fetch is None def test_process_notif_paused_on_finish(self): self._connect() @@ -1444,7 +1446,7 @@ def test_process_notif_paused_on_finish(self): self.proto.ps.pauseProducing() with patch("autopush.websocket.reactor") as mr: self.proto.finish_notifications(None) - ok_(mr.callLater.mock_calls > 0) + assert mr.callLater.mock_calls > 0 def test_notif_finished_with_webpush(self): self._connect() @@ -1453,7 +1455,7 @@ def test_notif_finished_with_webpush(self): self.proto.ps._check_notifications = True self.proto.ps.scan_timestamps = True self.proto.finish_notifications((None, [])) - ok_(self.proto.deferToLater.called) + assert self.proto.deferToLater.called def test_notif_finished_with_webpush_with_notifications(self): self._connect() @@ -1468,7 +1470,7 @@ def test_notif_finished_with_webpush_with_notifications(self): self.proto.ps.updates_sent[str(notif.channel_id)] = [] self.proto.finish_webpush_notifications((None, [notif])) - ok_(self.send_mock.called) + assert self.send_mock.called def test_notif_finished_with_webpush_with_old_notifications(self): self._connect() @@ -1485,8 +1487,8 @@ def test_notif_finished_with_webpush_with_old_notifications(self): self.proto.force_retry = Mock() self.proto.finish_webpush_notifications((None, [notif])) - ok_(self.proto.force_retry.called) - ok_(not self.send_mock.called) + assert self.proto.force_retry.called + assert not self.send_mock.called def test_notif_finished_with_too_many_messages(self): self._connect() @@ -1510,9 +1512,10 @@ def test_notif_finished_with_too_many_messages(self): d = Deferred() def check(*args, **kwargs): - eq_(self.metrics.increment.call_args[1]['tags'], ["source:Direct"]) - ok_(self.proto.force_retry.called) - ok_(self.send_mock.called) + assert self.metrics.increment.call_args[1]['tags'] == [ + "source:Direct"] + assert self.proto.force_retry.called + assert self.send_mock.called d.callback(True) self.proto.force_retry = Mock() @@ -1529,9 +1532,9 @@ def test_incomplete_uaid(self): } self.proto.ps.uaid = uaid reply = self.proto._verify_user_record() - eq_(reply, None) - ok_(fr.called) - eq_(fr.call_args[0], (mm.drop_user, uaid)) + assert reply is None + assert fr.called + assert fr.call_args[0] == (mm.drop_user, uaid) class RouterHandlerTestCase(unittest.TestCase): @@ -1553,23 +1556,23 @@ def test_client_connected(self): uaid = dummy_uaid_str self.app.clients[uaid] = client_mock = Mock(paused=False) resp = yield self.client.put(self.url(uaid=uaid), body="{}") - eq_(resp.get_status(), 200) - eq_(resp.content, "Client accepted for delivery") + assert resp.get_status() == 200 + assert resp.content == "Client accepted for delivery" client_mock.send_notification.assert_called_once() @inlineCallbacks def test_client_not_connected(self): resp = yield self.client.put(self.url(uaid=dummy_uaid_str), body="{}") - eq_(resp.get_status(), 404) - eq_(resp.content, "Client not connected.") + assert resp.get_status() == 404 + assert resp.content == "Client not connected." @inlineCallbacks def test_client_connected_but_busy(self): uaid = dummy_uaid_str self.app.clients[uaid] = Mock(accept_notification=False) resp = yield self.client.put(self.url(uaid=uaid), body="{}") - eq_(resp.get_status(), 503) - eq_(resp.content, "Client busy.") + assert resp.get_status() == 503 + assert resp.content == "Client busy." class NotificationHandlerTestCase(unittest.TestCase): @@ -1597,8 +1600,8 @@ def test_connected_and_free(self): uaid = dummy_uaid_str self.app.clients[uaid] = client_mock = Mock(paused=False) resp = yield self.client.put(self.url(uaid=uaid), body="{}") - eq_(resp.get_status(), 200) - eq_(resp.content, "Notification check started") + assert resp.get_status() == 200 + assert resp.content == "Notification check started" client_mock.process_notifications.assert_called_once() @inlineCallbacks @@ -1609,15 +1612,15 @@ def test_connected_and_busy(self): _check_notifications=False ) resp = yield self.client.put(self.url(uaid=uaid), body="{}") - eq_(resp.get_status(), 202) - eq_(resp.content, "Flagged for Notification check") - eq_(client_mock._check_notifications, True) + assert resp.get_status() == 202 + assert resp.content == "Flagged for Notification check" + assert client_mock._check_notifications is True @inlineCallbacks def test_not_connected(self): resp = yield self.client.put(self.url(uaid=dummy_uaid_str), body="{}") - eq_(resp.get_status(), 404) - eq_(resp.content, "Client not connected.") + assert resp.get_status() == 404 + assert resp.content == "Client not connected." @inlineCallbacks def test_delete(self): @@ -1630,6 +1633,6 @@ def test_delete(self): resp = yield self.client.delete( self.url(uaid=uaid, connected_at=str(now)) ) - eq_(resp.get_status(), 200) - eq_(resp.content, "Terminated duplicate") + assert resp.get_status() == 200 + assert resp.content == "Terminated duplicate" client_mock.sendClose.assert_called_once() diff --git a/test-requirements.txt b/test-requirements.txt index f1371d79..715df671 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -10,4 +10,6 @@ nose pbr==1.10.0 psutil pympler==0.5 +pytest +pytest-cov websocket-client