def test_new_device_replace_my_old_one(self):
        device1 = generate_device_info()
        device2 = generate_device_info()

        self.post(device1)
        self.post(device2)

        # The old device should not exist anymore
        self.assertEqual(Device.objects.filter(registration_id=device1["registration_id"]).count(), 0)

        # My device should be the new one
        self.assertEqual(Device.objects.filter(registration_id=device2["registration_id"], user=self.user).count(), 1)
    def test_registered_device_is_set_to_me(self):
        device = generate_device_info()

        self.post(device)
        self.assertEqual(
            Device.objects.get(registration_id=device["registration_id"]).user_id,
            self.user.id
        )
    def test_register_already_existing_device_set_it_to_me(self):
        device = generate_device_info()

        device1 = device.copy()
        device1["user"] = User.objects.last()
        Device(**device1).save()

        self.assertEqual(self.post(device).status_code, status.HTTP_201_CREATED)
        self.assertEqual(Device.objects.get(registration_id=device["registration_id"]).user_id, self.user.id)
    def test_try_to_send_deferred_messages_on_device_registration(self):
        self.mocked_send_fcm_message.return_value = dict(success=0)

        device = self.user.get_device()
        device.send_message()
        device.send_message()

        self.mocked_send_fcm_message.reset_mock()
        self.mocked_send_fcm_message.return_value = dict(success=1)

        self.post(generate_device_info(), url=API_V1 + "fcm/devices/")

        self.assertEqual(self.mocked_send_fcm_message.call_count, 2)
    def test_can_register_device(self):
        device = generate_device_info()

        self.assertEqual(self.post(device).status_code, status.HTTP_201_CREATED)
        self.assertEqual(Device.objects.filter(registration_id=device["registration_id"], user=self.user).count(), 1)