def test_sales_unit_api(admin_user):
    activate("en")
    get_default_shop()
    client = APIClient()
    client.force_authenticate(user=admin_user)

    sales_unit_data = {
        "translations": {
            "en": {"name": "Kilo", "symbol": "KG"}
        },
        "decimals": 2
    }
    response = client.post("/api/shuup/sales_unit/",
                           content_type="application/json",
                           data=json.dumps(sales_unit_data))
    assert response.status_code == status.HTTP_201_CREATED
    sales_unit = SalesUnit.objects.first()
    assert sales_unit.name == sales_unit_data["translations"]["en"]["name"]
    assert sales_unit.symbol == sales_unit_data["translations"]["en"]["symbol"]
    assert sales_unit.decimals == sales_unit_data["decimals"]

    sales_unit_data["translations"]["en"]["name"] = "Pound"
    sales_unit_data["translations"]["en"]["symbol"] = "PD"
    sales_unit_data["decimals"] = 3

    response = client.put("/api/shuup/sales_unit/%d/" % sales_unit.id,
                          content_type="application/json",
                          data=json.dumps(sales_unit_data))
    assert response.status_code == status.HTTP_200_OK
    sales_unit = SalesUnit.objects.first()
    assert sales_unit.name == sales_unit_data["translations"]["en"]["name"]
    assert sales_unit.symbol == sales_unit_data["translations"]["en"]["symbol"]
    assert sales_unit.decimals == sales_unit_data["decimals"]

    response = client.get("/api/shuup/sales_unit/%d/" % sales_unit.id)
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert sales_unit.name == data["translations"]["en"]["name"]
    assert sales_unit.symbol == data["translations"]["en"]["symbol"]
    assert sales_unit.decimals == data["decimals"]

    response = client.get("/api/shuup/sales_unit/")
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert sales_unit.name == data[0]["translations"]["en"]["name"]
    assert sales_unit.symbol == data[0]["translations"]["en"]["symbol"]
    assert sales_unit.decimals == data[0]["decimals"]

    response = client.delete("/api/shuup/sales_unit/%d/" % sales_unit.id)
    assert response.status_code == status.HTTP_204_NO_CONTENT
    assert SalesUnit.objects.count() == 0

    # create a product and relate it to a sales unit
    sales_unit = SalesUnit.objects.create(name="Kilo", symbol="KG")
    product = create_product("product with sales unit", sales_unit=sales_unit)

    # shouldn't be possible to delete a sales_unit with a related product
    response = client.delete("/api/shuup/sales_unit/%d/" % sales_unit.id)
    assert response.status_code == status.HTTP_400_BAD_REQUEST
    assert "This object can not be deleted because it is referenced by" in response.content.decode("utf-8")
Exemple #2
0
class RetentionPolicyTest(TestCase):
	def setUp(self):
		self.client = APIClient()
	
	def test_retention_create1(self):
		url = reverse('retention_policy-list')
		response = self.client.post(url, {'name': 'daily', 'duration': '01 00'}, format='json')
		self.assertEqual(response.status_code, status.HTTP_201_CREATED)
		response = self.client.post(url, {'name': 'daily', 'duration': '02 00'}, format='json')
		self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
		group1 = models.RetentionPolicy.objects.get(name="daily")
		self.assertEqual(group1.duration, timedelta(days=1))
		url = reverse('retention_policy-detail', args=['daily'])
		response = self.client.get(url, format='json')
		self.assertEqual(response.data['duration'], '1 00:00:00')
		self.assertEqual(response.status_code, status.HTTP_200_OK)
	def test_retention_delete1(self):
		group1 = models.RetentionPolicy.objects.create(id=123, name="test", duration=timedelta(days=1))
		url = reverse('retention_policy-detail', args=['test'])
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
		self.assertRaises(models.RetentionPolicy.DoesNotExist, models.RetentionPolicy.objects.get, name="test")
	def test_retention_delete2(self):
		# Retention deletion is protected by collection
		retention = models.RetentionPolicy.objects.create(name='daily', duration=timedelta(days=1))
		collection = models.Collection.objects.create(name='test', default_retention_policy=retention)
		url = reverse('retention_policy-detail', args=['daily'])
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
	def test_retention_delete3(self):
		# Retention deletion is protected by snapshot
		retention_daily  = models.RetentionPolicy.objects.create(name='daily',  duration=timedelta(days=1))
		retention_hourly = models.RetentionPolicy.objects.create(name='hourly', duration=timedelta(hours=1))
		collection = models.Collection.objects.create(name='test', default_retention_policy=retention_daily)
		snapshot = models.Snapshot.objects.create(collection = collection, retention_policy=retention_hourly)
		url = reverse('retention_policy-detail', args=['hourly'])
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
	def test_retention_purge1(self):
		file = ContentFile(b"123")
		file.name = "file.jpg"
		retention_daily  = models.RetentionPolicy.objects.create(name='daily',  duration=timedelta(days=1))
		retention_hourly = models.RetentionPolicy.objects.create(name='hourly', duration=timedelta(hours=1))
		collection = models.Collection.objects.create(name='test', default_retention_policy=retention_hourly)
		dates = [datetime.now(), datetime.now() - timedelta(minutes=30), datetime.now() - timedelta(minutes=90)]
		snapshots = [models.Snapshot.objects.create(collection = collection, date = x, file = file) for x in dates]
		snapshots.append(models.Snapshot.objects.create(collection = collection, date = dates[-1], retention_policy = retention_daily, file = file))
		storage2, filepath2 = snapshots[2].file.storage, snapshots[2].file.name
		url = reverse('retention_policy-purge', args=['hourly'])
		response = self.client.post(url)
		self.assertEqual(response.status_code, status.HTTP_201_CREATED)
		snapshots2 = models.Snapshot.objects.all()
		self.assertEqual(len(snapshots2), 3)
		self.assertEqual(snapshots2[0], snapshots[0])
		self.assertEqual(snapshots2[1], snapshots[1])
		self.assertEqual(snapshots2[2], snapshots[3])
		self.assertFalse(storage2.exists(filepath2))
Exemple #3
0
 def test_delete_locacao(self):
     cliente = models.Cliente.objects.create(nome='nome', cpf='1', tipo_cnh='A')
     veiculo = models.Veiculo.objects.create(nome='moto', categoria=u'Moto')
     locacao = models.Locacao.objects.create(cliente=cliente, veiculo=veiculo)
     pk = locacao.pk
     client = APIClient()
     client.delete('/locacao/locacao/{0}/'.format(pk))
     self.assertRaises(ObjectDoesNotExist, models.Locacao.objects.get, pk=pk)
Exemple #4
0
class PublishDeckTest(APITestCase):
    def setUp(self):
        self.superuser = User.objects.create_superuser('jdoe', '*****@*****.**', 'pass1234')
        self.client = APIClient()
        self.client.login(username='******', password='******')
        self.card = Card.objects.all()[0]
        self.land = Card.objects.filter(type__startswith="Basic Land")[0]

    def publishDeck(self):
        for i in range(2):
            response = self.client.post(reverse('collection-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        for i in range(3):
            response = self.client.post(reverse('collection-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = self.client.post(reverse('publish-deck', args=['my_deck']), {})
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def publishDeckTwiceFails(self):
        for i in range(2):
            response = self.client.post(reverse('collection-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        for i in range(3):
            response = self.client.post(reverse('collection-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = self.client.post(reverse('publish-deck', args=['my_deck']), {})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = self.client.post(reverse('publish-deck', args=['my_deck2']), {})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def deletePublishedDeck(self):
        for i in range(2):
            response = self.client.post(reverse('collection-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.card.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        for i in range(3):
            response = self.client.post(reverse('collection-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            response = self.client.post(reverse('deck-add-card', args=[self.land.id]), {})
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = self.client.post(reverse('publish-deck', args=['my_deck']), {})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = self.client.delete(reverse('publish-deck', args=['my_deck2']), {})
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def deletePublishedDeckWithNonePublishedSucceeds(self):
        response = self.client.delete(reverse('publish-deck', args=['my_deck2']), {})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemple #5
0
class TestAnswerViewSet(TestCase):

    def setUp(self):
        self.client = APIClient()

    def test_create(self):
        q = question(save=True)
        u = user(save=True)
        self.client.force_authenticate(user=u)
        data = {
            'question': q.id,
            'content': 'You just need to click the fox.',
        }
        eq_(Answer.objects.count(), 0)
        res = self.client.post(reverse('answer-list'), data)
        eq_(res.status_code, 201)
        eq_(Answer.objects.count(), 1)
        a = Answer.objects.all()[0]
        eq_(a.content, data['content'])
        eq_(a.question, q)

    def test_delete_permissions(self):
        u1 = user(save=True)
        u2 = user(save=True)
        a = answer(creator=u1, save=True)

        # Anonymous user can't delete
        self.client.force_authenticate(user=None)
        res = self.client.delete(reverse('answer-detail', args=[a.id]))
        eq_(res.status_code, 401)  # Unauthorized

        # Non-owner can't deletea
        self.client.force_authenticate(user=u2)
        res = self.client.delete(reverse('answer-detail', args=[a.id]))
        eq_(res.status_code, 403)  # Forbidden

        # Owner can delete
        self.client.force_authenticate(user=u1)
        res = self.client.delete(reverse('answer-detail', args=[a.id]))
        eq_(res.status_code, 204)  # No content

    def test_ordering(self):
        a1 = answer(save=True)
        a2 = answer(save=True)

        res = self.client.get(reverse('answer-list'))
        eq_(res.data['results'][0]['id'], a2.id)
        eq_(res.data['results'][1]['id'], a1.id)

        res = self.client.get(reverse('answer-list') + '?ordering=id')
        eq_(res.data['results'][0]['id'], a1.id)
        eq_(res.data['results'][1]['id'], a2.id)

        res = self.client.get(reverse('answer-list') + '?ordering=-id')
        eq_(res.data['results'][0]['id'], a2.id)
        eq_(res.data['results'][1]['id'], a1.id)
def test_manufacturer_api(admin_user):
    get_default_shop()
    client = APIClient()
    client.force_authenticate(user=admin_user)

    manufacturer_data = {
        "name": "manu 1",
        "url": "http://www.google.com"
    }
    response = client.post("/api/shuup/manufacturer/",
                           content_type="application/json",
                           data=json.dumps(manufacturer_data))
    assert response.status_code == status.HTTP_201_CREATED
    manufacturer = Manufacturer.objects.first()
    assert manufacturer.name == manufacturer_data["name"]
    assert manufacturer.url == manufacturer_data["url"]

    manufacturer_data["name"] = "name 2"
    manufacturer_data["url"] = "http://yahoo.com"

    response = client.put("/api/shuup/manufacturer/%d/" % manufacturer.id,
                          content_type="application/json",
                          data=json.dumps(manufacturer_data))
    assert response.status_code == status.HTTP_200_OK
    manufacturer = Manufacturer.objects.first()
    assert manufacturer.name == manufacturer_data["name"]
    assert manufacturer.url == manufacturer_data["url"]

    response = client.get("/api/shuup/manufacturer/%d/" % manufacturer.id)
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert manufacturer.name == data["name"]
    assert manufacturer.url == data["url"]

    response = client.get("/api/shuup/manufacturer/")
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert manufacturer.name == data[0]["name"]
    assert manufacturer.url == data[0]["url"]

    response = client.delete("/api/shuup/manufacturer/%d/" % manufacturer.id)
    assert response.status_code == status.HTTP_204_NO_CONTENT
    assert Manufacturer.objects.count() == 0

    # create a product and relate it to a manufacturer
    product = create_product("product with manufacturer")
    manufacturer = Manufacturer.objects.create()
    product.manufacturer = manufacturer
    product.save()

    # shouldn't be possible to delete a manufacturer with a related product
    response = client.delete("/api/shuup/manufacturer/%d/" % manufacturer.id)
    assert response.status_code == status.HTTP_400_BAD_REQUEST
    assert "This object can not be deleted because it is referenced by" in response.content.decode("utf-8")
    assert Manufacturer.objects.count() == 1
 def cleanUp(self):
     token = Token.objects.get(user__username='******')
     client = APIClient()
     client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
     url = reverse(
         'protocol-subject-view',
         kwargs={
             'pk': self.test_protocol.id,
             'subject': 2
         })
     client.delete(url)
Exemple #8
0
    def test_agentPermissions(self):
        # agent.py
        user = Account.objects.get(username="******")
        client = APIClient()
        client.force_authenticate(user=user)

        # create a agent for team, without code first
        url = "/api/v1/agents/agent/"
        data = {'agent_name': 'KAMIKAZE', 'team_name': 'XPTO1', 'language': 'Python'}
        response = client.post(path=url, data=data)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data, OrderedDict(
            [(u'agent_name', u'KAMIKAZE'), (u'language', 'Python'), (u'team_name', u'XPTO1')]))

        # create a agent for team, without code first
        url = "/api/v1/agents/agent/"
        data = {'agent_name': 'KAMIKAZE', 'team_name': 'XPTO2', 'language': 'Python'}
        response = client.post(path=url, data=data)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.data, {"detail": "You do not have permission to perform this action."})

        user = Account.objects.get(username="******")
        client2 = APIClient()
        client2.force_authenticate(user=user)

        url = "/api/v1/agents/agent/KAMIKAZE/?team_name=XPTO1"
        response = client2.get(path=url)
        self.assertEqual(response.data, {"detail": "You must be part of the team."})
        self.assertEqual(response.status_code, 403)

        url = "/api/v1/agents/agent/KAMIKAZE/?team_name=XPTO1"
        response = client2.delete(path=url)
        self.assertEqual(response.data, {u'detail': u'You do not have permission to perform this action.'})
        self.assertEqual(response.status_code, 403)

        url = "/api/v1/agents/validate_code/"
        data = {'agent_name': 'KAMIKAZE', 'team_name': 'XPTO1'}
        response = client2.post(path=url, data=data)
        self.assertEqual(response.data, {"detail": "You must be part of the team."})
        self.assertEqual(response.status_code, 403)

        # now with the team member must be possible to do
        url = "/api/v1/agents/agent/KAMIKAZE/?team_name=XPTO1"
        response = client.get(path=url)
        self.assertEqual(response.status_code, 200)

        url = "/api/v1/agents/agent/KAMIKAZE/?team_name=XPTO1"
        response = client.delete(path=url)
        self.assertEqual(response.data, {"status": "Deleted", "message": "The agent has been deleted"})
        self.assertEqual(Agent.objects.all().count(), 0)

        client.force_authenticate(user=None)
        client2.force_authenticate(user=None)
Exemple #9
0
def test_tax_class_api(admin_user):
    get_default_shop()
    client = APIClient()
    client.force_authenticate(user=admin_user)

    tax_class_data = {
        "translations": {
            "en": {"name": "tax class 1"}
        },
        "enabled": True
    }
    response = client.post("/api/shuup/tax_class/",
                           content_type="application/json",
                           data=json.dumps(tax_class_data))
    assert response.status_code == status.HTTP_201_CREATED
    tax_class = TaxClass.objects.first()
    assert tax_class.name == tax_class_data["translations"]["en"]["name"]
    assert tax_class.enabled == tax_class_data["enabled"]

    tax_class_data["translations"]["en"]["name"] = "Tax class 2"
    tax_class_data["enabled"] = False

    response = client.put("/api/shuup/tax_class/%d/" % tax_class.id,
                          content_type="application/json",
                          data=json.dumps(tax_class_data))
    assert response.status_code == status.HTTP_200_OK
    tax_class = TaxClass.objects.first()
    assert tax_class.name == tax_class_data["translations"]["en"]["name"]
    assert tax_class.enabled == tax_class_data["enabled"]

    response = client.get("/api/shuup/tax_class/%d/" % tax_class.id)
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert tax_class.name == data["translations"]["en"]["name"]
    assert tax_class.enabled == tax_class_data["enabled"]

    response = client.get("/api/shuup/tax_class/")
    assert response.status_code == status.HTTP_200_OK
    data = json.loads(response.content.decode("utf-8"))
    assert tax_class.name == data[0]["translations"]["en"]["name"]
    assert tax_class.enabled == data[0]["enabled"]

    response = client.delete("/api/shuup/tax_class/%d/" % tax_class.id)
    assert response.status_code == status.HTTP_204_NO_CONTENT
    assert TaxClass.objects.count() == 0

    tax_class = TaxClass.objects.create(name="class1")
    product = create_product("product1", tax_class=tax_class)
    # shouldn't be possible to delete a tax_class with a related product
    response = client.delete("/api/shuup/tax_class/%d/" % tax_class.id)
    assert response.status_code == status.HTTP_400_BAD_REQUEST
    assert "This object can not be deleted because it is referenced by" in response.content.decode("utf-8")
    def test_api_users_can_delete_user_on_delete_request(self):

        client = APIClient()

        self.client.post('/api/users/', data={'first_name': 'name1', 'last_name': 'name2',
                                              'other_name': 'name3', 'phone': '090896272',
                                              'gender': 'm', 'department': 'Deep Learning',
                                              'email': '*****@*****.**', 'password': '******',
                                              'confirm_password': '******'
                                              })

        client.delete('/api/users/', data={'email': '*****@*****.**'}, format='json')

        self.assertEqual(get_user_model().objects.count(), 0)
Exemple #11
0
class CollectionTest(TestCase):
	def setUp(self):
		self.client = APIClient()
		self.retention = models.RetentionPolicy.objects.create(name="daily", duration=timedelta(days=1))
	def tearDown(self):
		pass
	
	def assertEqualUrl(self, x, y):
		path_x = urlparse(x).path
		path_y = urlparse(y).path
		return self.assertEqual(path_x, path_y)
	def test_collection_create1(self):
		url = reverse('collection-list')
		retention_url = reverse('retention_policy-detail', args=('daily',))
		response = self.client.post(url, {'name': 'name1', 'default_retention_policy': retention_url}, format='json')
		self.assertEqual(response.status_code, status.HTTP_201_CREATED)
		response = self.client.post(url, {'name': 'name1', 'default_retention_policy': retention_url}, format='json')
		self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
		group1 = models.Collection.objects.get(name="name1")
		self.assertEqual(group1.default_retention_policy, self.retention)
		url = reverse('collection-detail', args=['name1'])
		response = self.client.get(url, format='json')
		self.assertEqual(response.status_code, status.HTTP_200_OK)
	def test_collection_get1(self):
		collection = models.Collection.objects.create(name="collection", default_retention_policy=self.retention)
		snapshots = []
		for i in range(0,3):
			snapshots.append(models.Snapshot.objects.create(collection = collection))
		url = reverse('collection-detail', args=('collection',))
		response = self.client.get(url)
		self.assertEqualUrl(response.data['begin'], reverse("snapshot-detail", args=(snapshots[0].id,)))
		self.assertEqualUrl(response.data['end'], reverse("snapshot-detail", args=(snapshots[2].id,)))
	def test_collection_head1(self):
		collection = models.Collection.objects.create(name="collection", default_retention_policy=self.retention)
		snapshots = []
		for i in range(0,3):
			snapshots.append(models.Snapshot.objects.create(collection = collection))
		url = reverse('collection-detail', args=('collection',))
		response = self.client.head(url)
		self.assertEqual(response.status_code, status.HTTP_200_OK)
		self.assertEqualUrl(response.data['begin'], reverse("snapshot-detail", args=(snapshots[0].id,)))
		self.assertEqualUrl(response.data['end'], reverse("snapshot-detail", args=(snapshots[2].id,)))
	def test_collection_delete1(self):
		group1 = models.Collection.objects.create(name="delete1", default_retention_policy=self.retention)
		url = reverse('collection-detail', args=['delete1'])
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
		response = self.client.delete(url)
		self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
		self.assertRaises(models.Collection.DoesNotExist, models.Collection.objects.get, name="delete1")
    def test_api_tasks_can_delete_task_on_delete_request(self):

        self.client.post('/account/login/', data={'email': '*****@*****.**', 'password': '******'})
        client = APIClient()

        self.client.post('/api/tasks/', data={'title': 'task a', "details": 'details a', "priority": '0',
                                              'status': '0', 'start_date': '2015-10-12',
                                              'expected_end_date': '2016-10-12'})

        saved_task = Task.objects.all()[0]

        client.delete('/api/tasks/', data={'id': '{}'.format(saved_task.id)}, format='json')

        self.assertEqual(Task.objects.count(), 0)
Exemple #13
0
class LinkApiTest(APITestCase):
    def setUp(self):
        self.admin = User.objects.create_superuser(username='******', email='*****@*****.**', password='******')
        self.client = APIClient()
        self.client.login(username='******', password='******')

    def test_creating_link(self):
        expected = 'test-detail'
        url = reverse('link-list')
        data = {'name': expected}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Link.objects.count(), 1)
        self.assertEqual(Link.objects.get().name, expected)

    def test_retrieving_link(self):
        retrieve_name = 'test-retrieve'
        Link.objects.create(name=retrieve_name, timestamp=datetime.date.today())
        response = self.client.get('/api/links/{}'.format(retrieve_name), format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_retrieving_unknown_link(self):
        response = self.client.get('/api/links/invalid', format='json')
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_deleting_link(self):
        delete_name = 'test-delete'
        Link.objects.create(name=delete_name, timestamp=datetime.date.today())
        response = self.client.delete('/api/links/{}'.format(delete_name))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #14
0
class GetAPITokenTest(TestCase):

  def setUp(self):
    self.client = APIClient()
    self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
    self.url = reverse('api:get_api_token')

  def test_get_api_token(self):
    self.client.login(username='******', password='******')
    response = self.client.get(self.url)
    token = Token.objects.get(user=self.user.id)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data['token'], token.key)
    self.client.logout()

  def test_post_api_token(self):
    self.client.login(username='******', password='******')
    response = self.client.post(self.url)
    self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

  def test_put_api_token(self):
    self.client.login(username='******', password='******')
    response = self.client.put(self.url)
    self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

  def test_delete_api_token(self):
    self.client.login(username='******', password='******')
    response = self.client.delete(self.url)
    self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Exemple #15
0
class GetVariableDetail(TestCase):

  def setUp(self):
    self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
    self.token = Token.objects.get(user=self.user.id)
    self.client = APIClient()
    self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
    self.dataset = Dataset(name='test_set', owner=self.user)
    self.dataset.save()
    self.variable = Variable(name='variable', dataset=self.dataset, datatype='string', values=['one', 'two', 'three'])
    self.variable.save()
    self.url = reverse('api:variable_by_dataset_detail', kwargs={'dataset_pk': self.dataset.id, 'pk':self.variable.id})
    
  def test_get_variable_detail(self):
    response = self.client.get(self.url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data['name'], self.variable.name)
    self.assertEqual(response.data['dataset'], self.variable.dataset.id)
    self.assertEqual(response.data['datatype'], self.variable.datatype)
    self.assertEqual(response.data['values'], self.variable.values)

  def test_modify_variable(self):
    data = {'name': 'changed_name', 'dataset':'changed_dataset', 'datatype':'float', 'subtype': 'continuous', 'values':[1, 2 , 3]}
    response = self.client.put(self.url, data)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data['name'], data['name'])
    self.assertEqual(response.data['dataset'], self.variable.dataset.id)
    self.assertEqual(response.data['datatype'], self.variable.datatype)
    self.assertEqual(response.data['values'], self.variable.values)
    self.assertEqual(response.data['subtype'], data['subtype'])

  def test_delete_variable(self):
    response = self.client.delete(self.url)
    self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
class AlbumTests(APITestCase):
    fixtures = ['core_initial_data_2.json']

    def setUp(self):
        # log in
        self.user = Account.objects.get(email='*****@*****.**')
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)

    def test_album_list(self):
        url = reverse('album-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_custom_album_create_delete(self):
        # Create custom album
        url = reverse('album-list')
        response = self.client.post(url, {'name': 'My custom album', 'description': 'My description', 'event': ''})
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # Now delete album
        url = response.data['url']
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_event_album_create(self):
        url = reverse('event-list')
        response = self.client.get(url)
        event_url = response.data['results'][0]['url']

        url = reverse('album-list')
        response = self.client.post(url, {'name': 'My event album', 'description': 'My event description', 'event': event_url})
        self.assertEqual(response.data['event'], event_url)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Exemple #17
0
 def test_remove_ban_at_a_member_with_unauthenticated_client(self):
     """
     Tries to remove a ban sanction at a member with a user isn't authenticated.
     """
     client = APIClient()
     response = client.delete(reverse('api-member-ban', args=[self.profile.pk]))
     self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Exemple #18
0
class ReferralApiTest(APITestCase):
    def setUp(self):
        self.admin = User.objects.create_superuser(username='******', email='*****@*****.**', password='******')
        self.client = APIClient()
        self.client.login(username='******', password='******')
        self.linkFk = Link.objects.create(name='test-fk')

    def test_creating_referral(self):
        expected_browser = 'test-browser'
        expected_ip_address = 'localhost'
        url = reverse('referral-list')
        data = {'browser': expected_browser, 'ip_address': expected_ip_address, 'link': str(self.linkFk.id)}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Referral.objects.count(), 1)
        self.assertEqual(Referral.objects.get().browser, expected_browser)
        self.assertEqual(Referral.objects.get().ip_address, expected_ip_address)

    def test_retrieving_referral(self):
        referral = Referral.objects.create(browser='test-browser', ip_address='localhost', link=self.linkFk,
                                           timestamp=datetime.date.today())
        response = self.client.get('/api/referrals/{}'.format(str(referral.id)), format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_retrieving_unknown_referral(self):
        response = self.client.get('/api/referrals/9999', format='json')
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_deleting_referral(self):
        referral = Referral.objects.create(browser='test-browser', ip_address='localhost', link=self.linkFk,
                                           timestamp=datetime.date.today())
        response = self.client.delete('/api/referrals/{}'.format(str(referral.id)))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #19
0
 def test_delete(self):
     client = APIClient()
     test_user = User.objects.get(username='******')
     client.force_authenticate(test_user)
     response = client.delete(SELF_PATH)
     assert response.status_code == status.HTTP_204_NO_CONTENT
     assert User.objects.filter(username='******').exists() == False
Exemple #20
0
    def test_make_sure_read_only_delete(self):
        movie_genre = MovieGenre(name='Comedy')
        movie_genre.save()

        client = APIClient()
        response = client.delete('/api/movies-genres/' + str(movie_genre.id))
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.data, {'detail': 'Authentication credentials were not provided.'})

        User.objects.create_user('admin-test', '*****@*****.**', 'password1234')
        client.login(username='******', password='******')
        response = client.delete('/api/movies-genres/' + str(movie_genre.id))
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.data, {'detail': 'You do not have permission to perform this action.'})
        self.assertEqual(len(MovieGenre.objects.all()), 1)
        self.assertEqual(MovieGenre.objects.get(id=movie_genre.id).name, 'Comedy')
def test_bug_job_map_delete(webapp, eleven_jobs_processed,
                            jm, mock_message_broker):
    """
    test retrieving a list of bug_job_map
    """
    client = APIClient()
    user = User.objects.create(username="******", is_staff=True)
    client.force_authenticate(user=user)

    job_id = jm.get_job_list(0, 1)[0]["id"]
    bug_id = random.randint(0, 100)

    jm.insert_bug_job_map(job_id, bug_id, "manual")

    pk = "{0}-{1}".format(job_id, bug_id)



    resp = client.delete(
        reverse("bug-job-map-detail", kwargs={
            "project": jm.project,
            "pk": pk
        })
    )

    user.delete()

    content = json.loads(resp.content)
    assert content == {"message": "Bug job map deleted"}

    jm.disconnect()
Exemple #22
0
class MarkElectedOtherUser(TestCase):
    """
    Tests marking an elected user. We use an extra user here to show that
    admin can not only mark himself but also other users.
    """
    def setUp(self):
        self.client = APIClient()
        self.client.login(username='******', password='******')
        self.assignment = Assignment.objects.create(title='test_assignment_Ierohsh8rahshofiejai', open_posts=1)
        self.user = get_user_model().objects.create_user(
            username='******',
            password='******')

    def test_mark_elected(self):
        self.assignment.set_candidate(get_user_model().objects.get(username='******'))
        response = self.client.post(
            reverse('assignment-mark-elected', args=[self.assignment.pk]),
            {'user': self.user.pk})

        self.assertEqual(response.status_code, 200)
        self.assertTrue(Assignment.objects.get(pk=self.assignment.pk).elected.filter(username='******').exists())

    def test_mark_unelected(self):
        user = get_user_model().objects.get(username='******')
        self.assignment.set_elected(user)
        response = self.client.delete(
            reverse('assignment-mark-elected', args=[self.assignment.pk]),
            {'user': self.user.pk})

        self.assertEqual(response.status_code, 200)
        self.assertFalse(Assignment.objects.get(pk=self.assignment.pk).elected.filter(username='******').exists())
def test_bug_job_map_delete_no_auth(jm, eleven_jobs_processed):
    """
    test retrieving a list of bug_job_map
    """
    client = APIClient()

    job_id = jm.get_job_list(0, 1)[0]["id"]
    bug_id = random.randint(0, 100)

    jm.insert_bug_job_map(job_id, bug_id, "manual")

    pk = "{0}-{1}".format(job_id, bug_id)



    resp = client.delete(
        reverse("bug-job-map-detail", kwargs={
            "project": jm.project,
            "pk": pk
        })
    )

    assert resp.status_code == 403

    jm.disconnect()
Exemple #24
0
    def test_add_movie_delete_different_user(self):
        User.objects.create_user('userA', '*****@*****.**', 'Apassword123')
        User.objects.create_user('userB', '*****@*****.**', 'Bpassword123')

        client = APIClient()
        client.login(username='******', password='******')

        response = client.post('/api/movies', {'title': 'Lion King',
                                               'summary': 'Lion Movie',
                                               'release_year': '1994',
                                               'rating': 2,
                                               'director': 'Roger Allers'})
        movie_id = response.data['id']

        self.assertEqual(response.status_code, 201)
        self.assertEqual(len(Movie.objects.all()), 1)
        # Logout of user A
        client.post('/rest-auth/logout/', {})
        # Login as user B
        client.login(username='******', password='******')
        # Should only be possible to delete movies that you have added
        response = client.delete('/api/movies/' + str(movie_id))

        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.data['detail'], 'You do not have permission to perform this action.')
        self.assertEqual(len(Movie.objects.all()), 1)
def test_bug_job_map_delete(webapp, eleven_jobs_stored, test_repository,
                            test_user, test_no_auth):
    """
    test deleting a bug_job_map object
    """
    job = Job.objects.all()[0]
    bug_id = random.randint(0, 100)

    BugJobMap.objects.create(job=job,
                             bug_id=bug_id,
                             user=test_user)

    client = APIClient()
    if not test_no_auth:
        client.force_authenticate(user=test_user)

    pk = "{0}-{1}".format(job.id, bug_id)

    resp = client.delete(
        reverse("bug-job-map-detail", kwargs={
            "project": test_repository.name,
            "pk": pk
        })
    )

    if test_no_auth:
        assert resp.status_code == 403
        assert BugJobMap.objects.count() == 1
    else:
        content = json.loads(resp.content)
        assert content == {"message": "Bug job map deleted"}
        assert BugJobMap.objects.count() == 0
    def test_processing(self):
        taxi_id1 = 1
        taxi_id2 = 2
        passenger_id = 1
        client = APIClient()

        response = client.post('/taxi/%d/location/' % taxi_id1, {'lat': 56.312719, 'lon': 43.845431}, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        response = client.post('/taxi/%d/location/' % taxi_id2, {'lat': 55.312719, 'lon': 41.845431}, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(TaxiLocation.objects.count(), 2)

        response = client.post('/passenger/%s/order/' % passenger_id, {'lat': 56.315855, "lon": 44.003525},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(PassengerOrder.objects.count(), 1)

        process_passengers()

        order = PassengerOrder.objects.get(passenger_id=passenger_id)
        self.assertEqual(int(order.taxi_id), taxi_id1)
        taxi = TaxiLocation.objects.get(taxi_id=taxi_id1)
        self.assertTrue(taxi.is_busy)

        # test delete
        response = client.delete('/passenger/%s/order/' % passenger_id, format='json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(PassengerOrder.objects.count(), 0)
        taxi = TaxiLocation.objects.get(taxi_id=taxi_id1)
        self.assertFalse(taxi.is_busy)
Exemple #27
0
class APITestCase(APITestCase):
    fixtures = ['user.json','robot.json']

    def setUp(self):
        user = User.objects.get(username='******')
        self.client = APIClient()
        self.client.force_authenticate(user=user)

    def test_get_robots(self):
        """Ensure we can get a robot list in the full API"""
        url = reverse('robots_list')
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create_robot(self):
        """Ensure we can get a specific robot"""
        url = reverse('robots_list')
        data = {'username': '******','robot_path':'test'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['robot_path'], data['robot_path'])

    def test_delete_robot(self):
        url = reverse('robots_detail', kwargs={'pk':'1'})
        response = self.client.delete(url, format='json')
        self.assertEqual(url,'/robots/1')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_get_user(self):
        """Ensure we can get a single user in the full API"""
        url = reverse('users_list')
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
class TeamMemberTest(TestCase):

    def setUp(self):
        self.client = APIClient()

    def test_new_teammember(self):
        team_member_data = {
            "first_name": "Bob",
            "last_name": "Smitty",
            "gender": "M",
            "birth_year": 1901,
            "mobile": "+4917579",
            "email": "*****@*****.**"
        }
        response = self.client.post('/dashboard/teammembers/', team_member_data)
        self.assertEqual(response.status_code, 201)

    def test_can_change(self):
        # This makes me sad, but is in the spec currently until we use passwords.
        team_member_data = {
            "first_name": "Bob",
            "last_name": "Smitty",
            "gender": "M",
            "birth_year": 1901,
            "mobile": "+4917579",
            "email": "*****@*****.**"
        }
        response = self.client.post('/dashboard/teammembers/', team_member_data)

        assert 'Location' in response
        tm_url = response['Location']

        response = self.client.patch(tm_url, {'first_name': 'Robert'})
        self.assertEqual(json.loads(response.content)['firstName'], 'Robert')

    def test_can_delete(self):
        # This makes me sad, but is in the spec currently. At least until we use passwords.
        team_member_data = {
            "first_name": "Bob",
            "last_name": "Smitty",
            "gender": "M",
            "birth_year": 1901,
            "mobile": "+4917579",
            "email": "*****@*****.**"
        }
        response = self.client.post('/dashboard/teammembers/', team_member_data, format='json')

        response = self.client.delete(response['Location'], format='json')
        self.assertEqual(response.status_code, 204)

    def test_creating_mobile_is_optional(self):
        team_member_data = {
            "first_name": "Bob",
            "last_name": "Smitty",
            "gender": "M",
            "birth_year": 1901,
            "email": "*****@*****.**"
        }
        response = self.client.post('/dashboard/teammembers/', team_member_data, format='json')
        self.assertEqual(response.status_code, 201)
Exemple #29
0
    def test_only_me_can_delete_account(self):
        """
        Accounts can only be deleted by authed owner
        :return:
        """
        # setup
        self.test_create_account()
        view = AccountViewSet.as_view({'delete': 'destroy'})
        account = Account.objects.get(username=self.username)
        client = APIClient()

        # auth with jwt
        response = client.post('/api-token-auth/',
                               self.json_account_credentials,
                               format='json')

        token = response.data['token']
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Make request
        client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
        response = client.delete('/api/v1/accounts/'+self.username+'/')
        # Asserts
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        # check no object exists
        try:
            account = Account.objects.get(username=self.username)
        except:
            account = None
        self.assertIsNone(account)
Exemple #30
0
    def test_uploading_a_document_using_token_auth(self):
        # Get the an user token
        token_client = APIClient()
        response = token_client.post(reverse('auth_token_obtain'), {'username': TEST_ADMIN_USERNAME, 'password': TEST_ADMIN_PASSWORD})

        # Be able to get authentication token
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Make a token was returned
        self.assertTrue(u'token' in response.content)

        token = loads(response.content)['token']

        # Create a new client to simulate a different request
        document_client = APIClient()

        # Create a blank document with no token in the header
        response = document_client.post(reverse('document-list'), {'description': 'test document'})

        # Make sure toke authentication is working, should fail
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        document_client.credentials(HTTP_AUTHORIZATION='Token ' + token)

        # Create a blank document
        document_response = document_client.post(reverse('document-list'), {'description': 'test document'})
        self.assertEqual(document_response.status_code, status.HTTP_201_CREATED)

        # The document was created in the DB?
        self.assertEqual(Document.objects.count(), 1)

        new_version_url = loads(document_response.content)['new_version']

        with open(TEST_DOCUMENT_PATH) as file_descriptor:
            response = document_client.post(new_version_url, {'file': file_descriptor})

        # Make sure the document uploaded correctly
        document = Document.objects.first()
        self.failUnlessEqual(document.exists(), True)
        self.failUnlessEqual(document.size, 272213)

        self.failUnlessEqual(document.file_mimetype, 'application/pdf')
        self.failUnlessEqual(document.file_mime_encoding, 'binary')
        self.failUnlessEqual(document.file_filename, 'mayan_11_1.pdf')
        self.failUnlessEqual(document.checksum, 'c637ffab6b8bb026ed3784afdb07663fddc60099853fae2be93890852a69ecf3')
        self.failUnlessEqual(document.page_count, 47)

        # Make sure we can edit the document via the API
        document_url = loads(document_response.content)['url']

        response = document_client.post(document_url, {'description': 'edited test document'})

        self.assertTrue(document.description, 'edited test document')

        # Make sure we can delete the document via the API
        response = document_client.delete(document_url)

        # The document was deleted from the the DB?
        self.assertEqual(Document.objects.count(), 0)
Exemple #31
0
class TestViews(APITestCase):

    def setUp(self):
        self.client = APIClient()
        user_password = '******'
        user = User.objects.create_user(
            username='******',
            email='*****@*****.**',
            password=user_password,
            is_active=True
        )
        url = reverse('token_obtain_pair')
        response = self.client.post(url, 
            {'username': user.username, 'password': user_password}
        )
        access_token = response.json().get('access')
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + access_token)
        
        self.product = Product.objects.create(
            name='manzana',
            price=12.76,
            stock=34
        )

        self.order = Order.objects.create()

        self.order_detail = OrderDetail.objects.create(
            product=self.product,
            quantity=10,
            order=self.order
        )

    def test_create_order(self):
        url = reverse('orders:order-list')
        data = {
            'product': self.product.pk,
            'quantity': 20
        }
        response = self.client.post(url, data)
        order_data = response.json()

        self.assertEquals(response.status_code, status.HTTP_201_CREATED)
        self.assertEquals(order_data['pk'], Order.objects.get(pk=order_data['pk']).pk)
        self.assertEquals(order_data['order_detail'], [])
        self.assertEquals(order_data['pesos_total'], 0)
        self.assertEquals(order_data['usd_total'], 0)
      
    def test_delete_order(self):
        url = reverse('orders:order-detail', args=[self.order_detail.order.pk])
        response = self.client.delete(url)

        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEquals(response.status_text, 'No Content')

    def test_update_order(self):
        url = reverse('orders:order-detail', args=[self.order_detail.order.pk])
        data = {
            'product': self.order_detail.product.pk,
            'quantity': 5
        }        
        response = self.client.put(url, data)
        _response = response.json()

        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(_response['pk'], self.order_detail.order.pk)
        self.assertEquals(_response['order_detail'][0]['quantity'], 5)
        self.assertEquals(_response['order_detail'][0]['product']['pk'], self.order_detail.product.pk)
        self.assertEquals(_response['usd_total'], self.order_detail.order.usd_total)
        self.assertEquals(_response['pesos_total'], self.order_detail.order.pesos_total)

    def test_add_product_to_order(self):
        product = Product.objects.create(
            name='pera',
            price=10.50,
            stock=600
        )    
        url = reverse('orders:order-detail', args=[self.order_detail.order.pk])
        data = {
            'product': product.pk,
            'quantity': 5
        }

        response = self.client.put(url, data)
        _response = response.json()

        for r in _response['order_detail']:
            if r['product']['pk']==product.pk:
                _order_detail = _response['order_detail'][0]

        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(_response['pk'], self.order_detail.order.pk)
        self.assertEquals(_order_detail['quantity'], 5)
        self.assertEquals(_order_detail['product']['pk'], product.pk)
        self.assertEquals(_response['usd_total'], self.order_detail.order.usd_total)
        self.assertEquals(_response['pesos_total'], self.order_detail.order.pesos_total)

    def test_get_specific_order(self):
        url = reverse('orders:order-detail', args=[self.order_detail.order.pk])
        response = self.client.get(url)
        _response = response.json()

        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertEquals(_response['pk'], self.order_detail.order.pk)
        self.assertEquals(_response['order_detail'][0]['quantity'], 10)
        self.assertEquals(_response['order_detail'][0]['product']['pk'], self.order_detail.product.pk)
        self.assertEquals(_response['usd_total'], self.order_detail.order.usd_total)
        self.assertEquals(_response['pesos_total'], self.order_detail.order.pesos_total)        
class OrderTestCases(TestCase):

    fixtures = ['ayofixture.json']

    def setUp(self):
        self.customer_client = APIClient()
        self.customervals = self.customer_client.post(reverse('login'), {
            "username": "******",
            "password": "******"
        },
                                                      format="json")
        self.customer_jwt_access = self.customervals.data['jwt']['access']
        self.customer_client.credentials(HTTP_AUTHORIZATION="Bearer " +
                                         self.customer_jwt_access)

        self.worker_client = APIClient()
        self.workervals = self.customer_client.post(reverse('login'), {
            "username": "******",
            "password": "******"
        },
                                                    format="json")
        self.worker_jwt_access = self.workervals.data['jwt']['access']
        self.worker_client.credentials(HTTP_AUTHORIZATION="Bearer " +
                                       self.worker_jwt_access)

    def test_add_prescitem(self):
        response = self.customer_client.post(
            reverse('add_prescitem'), {
                "name": "test medicine",
                "fprescuency": "Once a day",
                "quantity_to_buy": 10,
                "quantity_to_take": 10,
                "first_dose": "2021-05-13T07:37:18Z",
                "customer_id": self.customervals.data['id']
            })

        self.assertEquals(response.data['quantity_to_take'], 10)

    def test_get_free_prescitems(self):
        response2 = self.customer_client.get(
            reverse('get_free_prescitems',
                    kwargs={"userid": self.customervals.data['id']}))
        self.assertEquals(response2.status_code, 200)

    def test_edit_free_prescitems(self):
        response2 = self.customer_client.get(
            reverse('get_free_prescitems',
                    kwargs={"userid": self.customervals.data['id']})).data
        response3 = self.customer_client.patch(reverse(
            'instance_prescitems', kwargs={"prescitem": response2[0]['id']}),
                                               {"quantity_to_take": 25},
                                               format="json")
        self.assertEquals(response3.data['quantity_to_take'], 25)

    def test_delete_free_prescitems(self):
        response2 = self.customer_client.get(
            reverse('get_free_prescitems',
                    kwargs={"userid": self.customervals.data['id']})).data
        response3 = self.customer_client.delete(
            reverse('instance_prescitems',
                    kwargs={"prescitem": response2[0]['id']}))
        self.assertEquals(response3.data, "Deleted")

    def test_user_prescriptions(self):
        response2 = self.customer_client.get(
            reverse('get_user_prescriptions',
                    kwargs={"userid": self.customervals.data['id']}))
        self.assertEquals(response2.status_code, 200)

    def test_add_photo_prescription(self):
        response2 = self.customer_client.post(
            reverse('add_prescription'), {
                "customer_id":
                self.customervals.data['id'],
                "starting_date":
                "2021-05-13T07:37:18Z",
                "prescription_photo":
                "https://i.ytimg.com/vi/7eGKDuJ-E1w/hqdefault.jpg",
            })
        self.assertEquals(response2.status_code, 200)

    def test_add_copy_prescription(self):
        response2 = self.customer_client.post(
            reverse('add_prescription'), {
                "customer_id": self.customervals.data['id'],
                "starting_date": "2021-05-13T07:37:18Z",
                "prescription_copy":
                "http://africau.edu/images/default/sample.pdf"
            })
        self.assertEquals(response2.status_code, 200)

    def test_edit_prescription(self):
        response = self.customer_client.get(
            reverse("get_user_prescriptions",
                    kwargs={"userid": self.customervals.data['id']}))

        response2 = self.customer_client.patch(
            reverse('instance_prescription',
                    kwargs={"prescription": response.data[0]['id']}), {
                        "starting_date": "2021-06-13T07:37:18Z",
                    })
        self.assertEquals(response2.status_code, 202)
Exemple #33
0
class LampsTests(TestCase):
    def setUp(self):
        user = User.objects.create_user('testuser')
        self.client = APIClient()
        self.client.force_authenticate(user=user)

    def test_root(self):
        response = self.client.get('/api/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual('application/json', response['Content-Type'])
        self.assertIn('lamps', response.json())

    def test_list_basics(self):
        lamps = [Lamp.objects.create(name=f'lamp{i}') for i in range(3)]

        response = self.client.get('/api/lamps/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        data = response.json()
        self.assertEqual(data['count'], len(lamps))

    def test_list_lamp_repr(self):
        lamp = Lamp.objects.create(name='lamp1')

        response = self.client.get('/api/lamps/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = response.json()
        lamp_repr = data['results'][0]
        self.assertEqual(lamp_repr['name'], lamp.name)
        self.assertEqual(lamp_repr['is_on'], lamp.is_on)
        self.assertEqual(lamp_repr['brightness'], lamp.brightness)
        self.assertIn('url', lamp_repr)

    def test_lamp_details(self):
        lamp = Lamp.objects.create(name='lamp1',
                                   is_on=True,
                                   last_switch=timezone.now())

        response = self.client.get('/api/lamps/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp_url = response.json()['results'][0]['url']

        response = self.client.get(lamp_url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp_repr = response.json()
        self.assertEqual(lamp_repr['name'], lamp.name)
        self.assertEqual(lamp_repr['is_on'], lamp.is_on)
        self.assertEqual(lamp_repr['brightness'], lamp.brightness)
        self.assertEqual(lamp_repr['url'], lamp_url)
        self.assertEqual(datetime.fromisoformat(lamp_repr['last_switch']),
                         lamp.last_switch)
        self.assertEqual(lamp_repr['total_working_time'], '00:00:00')

    def test_turn_on(self):
        brightness = 15
        lamp = Lamp.objects.create(name='lamp1',
                                   is_on=False,
                                   brightness=brightness)

        response = self.client.get('/api/lamps/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp_url = response.json()['results'][0]['url']
        response = self.client.patch(lamp_url, {'is_on': True})
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp.refresh_from_db()
        self.assertEqual(lamp.is_on, True)
        self.assertIsNotNone(lamp.last_switch)
        self.assertEqual(lamp.brightness,
                         brightness,
                         msg='partial update should not change other fields')

    def test_change_brightness(self):
        old_brightness = 50
        new_brightness = 60
        lamp = Lamp.objects.create(name='lamp1', brightness=old_brightness)

        response = self.client.get('/api/lamps/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp_url = response.json()['results'][0]['url']
        response = self.client.patch(lamp_url, {'brightness': new_brightness})
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        lamp.refresh_from_db()
        self.assertEqual(lamp.brightness, new_brightness)
        self.assertIsNone(
            lamp.last_switch,
            'change of brightness should not update "last_switch"')

    def test_post(self):
        response = self.client.post('/api/lamps/', {'name': 'lamp name'})
        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)

    def test_delete(self):
        lamp = Lamp.objects.create(name='lamp1')
        response = self.client.delete(f'/api/lamps/{lamp.id}/')
        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)

    def test_change_name(self):
        name = 'the lamp'
        lamp = Lamp.objects.create(name=name)
        response = self.client.patch(f'/api/lamps/{lamp.id}/',
                                     {'name': 'new name'})
        # DRF default behaviour is to silently ignore changes to
        # read-only fields. I'm fine with that.
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        lamp.refresh_from_db()
        self.assertEqual(lamp.name, name)

    @mock.patch('lights.services.lamp_service.switch')
    def test_switch_error(self, mock_switch):
        mock_switch.turn_on.side_effect = SwitchError('switch error')
        lamp = Lamp.objects.create(name='lamp1')
        # TODO: extract reverse method
        response = self.client.patch(f'/api/lamps/{lamp.id}/', {'is_on': True})
        self.assertEqual(response.status_code,
                         status.HTTP_503_SERVICE_UNAVAILABLE)

    def test_turn_on_404(self):
        """Test turning on a non-existent lamp."""
        response = self.client.patch(f'/api/lamps/100/', {'is_on': True})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class UsersIdTests(APITestCase):
    @classmethod
    def setUpClass(cls):
        super(UsersIdTests, cls).setUpClass()
        cls.user_attrs = [
            'id',
            'url',
            'email',
            'first_name',
            'last_name',
            'is_active',
            'phone',
            'other_phone',
            'is_superuser',
            'is_staff',
            'last_login',
            'date_joined',
            'gender',
            'birthdate',
            'groups',
            'user_permissions',
        ]

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

    def test_retrieve_user_id_not_exist(self):
        """
        Ensure we can't retrieve a user that doesn't exist.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(reverse(
            'user-detail',
            kwargs={'pk': 999},
        ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_user_id_not_exist_without_permission(self):
        """
        Ensure we can't know a user doesn't exist without permission
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse(
            'user-detail',
            kwargs={'pk': 999},
        ))

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_retrieve_user(self):
        """
        Ensure we can retrieve a user.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ))

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], 1)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_retrieve_user_profile(self):
        """
        Ensure we can retrieve our details through /profile.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('profile', ))

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], 1)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_partial_update_user_with_permission(self):
        """
        Ensure we can update a specific user if caller has permission.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check if update was successful
        self.assertEqual(content['phone'], data['phone'])

        # Check id of the user
        self.assertEqual(content['id'], 1)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_partial_update_user_with_permission_change_password(self):
        """
        Ensure we can change password if current password is provided and the
        new password is validated.
        """

        data = {"password": "******", "new_password": "******"}

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], 1)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        self.user.refresh_from_db()

        # Ensure that the password has been changed successfully
        self.assertTrue(self.user.check_password("!321tseT"))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_user_with_permission(self):
        """
        Ensure we can update a specific user if caller has permission.
        Put requires a full update, including password.
        """
        data = {
            'password': '******',
            'new_password': '******',
            'phone': '1234567890',
            'first_name': 'Chuck',
            'last_name': 'Norris',
            'gender': "M",
            'birthdate': "1999-11-11",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.put(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        self.user.refresh_from_db()

        # Check if update was successful
        self.assertEqual(content['phone'], data['phone'])
        self.assertTrue(self.user.check_password("!321tset"))

        # Check id of the user
        self.assertEqual(content['id'], 1)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_user_without_permission(self):
        """
        Ensure we can't update a specific user doesn't have permission.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.admin.id},
            ),
            data,
            format='json',
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_non_existent_user(self):
        """
        Ensure we get permission denied when trying to update an invalid user.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': 9999},
            ),
            data,
            format='json',
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_non_existent_user_as_admin(self):
        """
        Ensure we get not found when trying to update an invalid user as
        an admin.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': 9999},
            ),
            data,
            format='json',
        )

        content = {'detail': 'Not found.'}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_user_weak_new_password(self):
        """
        Ensure we can't update our password if it is not validated.
        """

        data = {
            "phone": "1234567890",
            "password": "******",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {
            'new_password': [
                'This password is too common.',
                'This password is entirely numeric.'
            ]
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_missing_old_password(self):
        """
        Ensure we can't update our password if the current one is not provided.
        """

        data = {
            "phone": "1234567890",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'password': '******'}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_wrong_old_password(self):
        """
        Ensure we can't update our password if the current one is wrong.
        """

        data = {
            "phone": "1234567890",
            "password": "******",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'password': '******'}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_invalid_fields(self):
        """
        Ensure we can't update fields with invalid values.
        """

        data = {
            'email': '*****@*****.**',
            'password': '******',
            'first_name': 'Chuck',
            'last_name': 'Norris',
            'gender': "invalid_gender",
            'birthdate': "invalid_date",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {
            'birthdate': [
                'Date has wrong format. Use one of these formats instead: '
                'YYYY-MM-DD.'
            ],
            'gender': ['"invalid_gender" is not a valid choice.']
        }

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_delete_user_as_admin(self):
        """
        Ensure we can deactivate a user as an admin.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ), )
        self.user.refresh_from_db()

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(self.user.is_active)

        self.user.is_active = True
        self.user.refresh_from_db()

    def test_delete_user(self):
        """
        Ensure that a user can't deactivate its own account.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ), )
        self.user.refresh_from_db()

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(self.user.is_active)

        self.user.is_active = True
        self.user.refresh_from_db()

    def test_delete_inexistent_user(self):
        """
        Ensure that deleting a non-existent user does nothing.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': 999},
            ), )

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #35
0
class FoundNoticeTestCase(APITestCase):
    def setUp(self):
        self.client = APIClient()

        self.user = User.objects.create(username='******',
                                        password=make_password('secret'),
                                        first_name='Thu',
                                        last_name='Student',
                                        is_verified=True,
                                        status='ACT',
                                        is_staff=False,
                                        is_superuser=False,
                                        date_joined=make_aware(datetime.now()))
        self.property_type = PropertyType.objects.create(name='electronic')
        self.property_template = PropertyTemplate.objects.create(
            name='iphone', type=self.property_type, fields='{"serial": 123}')

        self.notice = FoundNotice.objects.create(
            property=Property.objects.create(name='My Iphone',
                                             template=self.property_template,
                                             attributes='{"serial": 123}'),
            found_location='{"name": "清华大学紫荆学生公寓4号楼","address": "北京市海淀区 ", \
                          "latitude": 40.0104, "longitude": 116.327391}"',
            found_datetime='2020-02-20 11:11',
            author=self.user)

        refresh = RefreshToken.for_user(self.user)
        self.client.credentials(
            HTTP_AUTHORIZATION=f'Bearer {refresh.access_token}')

    def test_create(self):
        data = {
            "contacts": [{
                "name": "bob",
                "method": "PHN",
                "details": "1234"
            }],
            "property": {
                "template": "iphone",
                "tags": [],
                "name": "My New Iphone",
                "attributes": {
                    "serial": 123
                },
                "description": "My Lost Iphone"
            },
            "description": "My Found Notice",
            "found_datetime": "2020-02-20 11:11",
            "found_location": '{"name": "清华大学紫荆学生公寓4号楼","address": "北京市海淀区 ", \
                          "latitude": 40.0104, "longitude": 116.327391}"',
            "status": "PUB"
        }
        response = self.client.post('/api/v1/found-notices/',
                                    data=data,
                                    format='json')
        self.assertEqual(response.status_code, 201)
        get_response = self.client.get('/api/v1/found-notices/2/?format=json')
        self.assertEqual(get_response.status_code, 200)
        self.assertEqual(get_response.json()['id'], 2)

    def test_list(self):
        response = self.client.get('/api/v1/found-notices/?format=json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.json()['results']), 1)

    def test_detail(self):
        response = self.client.get(
            f'/api/v1/found-notices/{self.notice.id}/?format=json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['id'], self.notice.id)

    def test_update(self):
        data = {
            "contacts": [{
                "name": "bob",
                "method": "PHN",
                "details": "1234"
            }],
            "property": {
                "template": "iphone",
                "tags": [],
                "name": "My New Iphone",
                "attributes": {
                    "serial": 123
                },
                "description": "My Lost Iphone"
            },
            "description": "My New Description",
            "found_datetime": "2020-02-20 11:11",
            "found_location": '{"name": "清华大学紫荆学生公寓4号楼","address": "北京市海淀区 ", \
                          "latitude": 40.0104, "longitude": 116.327391}"',
            "status": "PUB"
        }
        response = self.client.patch(
            f'/api/v1/found-notices/{self.notice.id}/?format=json',
            data=data,
            format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['description'], 'My New Description')

    def test_change_status(self):
        response = self.client.post(
            f'/api/v1/found-notices/{self.notice.id}/change-status/?format=json',
            {'status': 'CLS'})
        self.assertEqual(response.status_code, 200)
        get_response = self.client.get(
            f'/api/v1/found-notices/{self.notice.id}/?format=json')
        self.assertEqual(get_response.status_code, 200)
        self.assertEqual(get_response.json()['status'], 'CLS')

    def test_delete(self):
        response = self.client.delete(
            f'/api/v1/found-notices/{self.notice.id}/?format=json')
        self.assertEqual(response.status_code, 204)
        get_response = self.client.get('/api/v1/found-notices/?format=json')
        self.assertEqual(get_response.status_code, 200)
        self.assertEqual(len(get_response.json()['results']), 0)
Exemple #36
0
class TagViewTestCase(TestCase):
    """Test suite for the api Tag views."""
    def setUp(self):
        """Define the test client and other test variables."""
        user = User.objects.create_user(username="******")

        # Initialize client and force it to use authentication
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        # Create a new account.
        self.account = Account(name="Dummy Account1234")
        self.account.save()

        # Create new category.
        self.category = Category(name="Dummy category1234")
        self.category.save()

        # Create new transactionstatus.
        self.transactionstatus = TransactionStatus(name="Dummy status 1234")
        self.transactionstatus.save()

        # Create new transaction.
        self.transaction = Transaction(
            transaction_date=timezone.now(),
            original_description='Dummy Transaction124',
            account=self.account,
            category=self.category,
            transactionstatus=self.transactionstatus)
        self.transaction.save()

        self.data = {
            'transaction_id': self.transaction.id,
            'tag_name': 'Dummy Tag Name 123'
        }

        self.response = self.client.post(reverse('tag-list'),
                                         self.data,
                                         format="json")

    def test_api_can_create_tag(self):
        """Test the api has tag creation capability."""
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    def test_authorization_is_enforced(self):
        """Test that the api has user authorization."""
        new_client = APIClient()
        response = new_client.get(reverse('tag-detail', kwargs={'pk': 3}),
                                  format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_api_can_get_tag(self):
        """Test the api can get a given tag."""
        tag = Tag.objects.get()
        response = self.client.get(reverse('tag-detail', kwargs={'pk':
                                                                 tag.id}),
                                   format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, tag)

    def test_api_can_update_tag(self):
        """Test the api can update a given tag."""
        tag = Tag.objects.get()
        change_tag = {
            'transaction_id': self.transaction.id,
            'tag_name': 'Changed Tag Name'
        }
        res = self.client.put(reverse('tag-detail', kwargs={'pk': tag.id}),
                              change_tag,
                              format='json')
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_api_can_delete_tag(self):
        """Test the api can delete a tag."""
        tag = Tag.objects.get()
        response = self.client.delete(reverse('tag-detail',
                                              kwargs={'pk': tag.id}),
                                      format='json',
                                      follow=True)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #37
0
    def test_write_cost_model_rate_rbac_access(self):
        """Test POST, PUT, and DELETE for rates with an rbac user."""
        # create a rate as admin
        user_data = self._create_user_data()
        customer = self._create_customer_data()

        admin_request_context = self._create_request_context(
            customer, user_data, create_customer=True, is_admin=True)
        with patch.object(RbacService,
                          "get_access_for_user",
                          return_value=None):
            url = reverse("costmodels-list")
            client = APIClient()

            response = client.post(url,
                                   data=self.fake_data,
                                   format="json",
                                   **admin_request_context["request"].META)
            cost_model_uuid = response.data.get("uuid")
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        user_data = self._create_user_data()

        request_context = self._create_request_context(customer,
                                                       user_data,
                                                       create_customer=False,
                                                       is_admin=False)

        self.initialize_request(context={
            "request_context": request_context,
            "user_data": user_data
        })

        # POST tests
        test_matrix = [
            {
                "access": {
                    "rate": {
                        "read": [],
                        "write": []
                    }
                },
                "expected_response": status.HTTP_403_FORBIDDEN,
                "metric": {
                    "name": CostModelMetricsMap.OCP_METRIC_CPU_CORE_USAGE_HOUR
                },
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": ["*"]
                    }
                },
                "expected_response": status.HTTP_201_CREATED,
                "metric": {
                    "name":
                    CostModelMetricsMap.OCP_METRIC_CPU_CORE_REQUEST_HOUR
                },
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": ["*"]
                    }
                },
                "expected_response": status.HTTP_201_CREATED,
                "metric": {
                    "name": CostModelMetricsMap.OCP_METRIC_MEM_GB_REQUEST_HOUR
                },
            },
        ]
        client = APIClient()
        other_cost_models = []

        for test_case in test_matrix:
            with patch.object(RbacService,
                              "get_access_for_user",
                              return_value=test_case.get("access")):
                url = reverse("costmodels-list")
                rate_data = copy.deepcopy(self.fake_data)
                rate_data["rates"][0]["metric"] = test_case.get("metric")
                caches["rbac"].clear()
                response = client.post(url,
                                       data=rate_data,
                                       format="json",
                                       **request_context["request"].META)

                self.assertEqual(response.status_code,
                                 test_case.get("expected_response"))
                if response.data.get("uuid"):
                    other_cost_models.append(response.data.get("uuid"))

        # PUT tests
        test_matrix = [
            {
                "access": {
                    "rate": {
                        "read": [],
                        "write": []
                    }
                },
                "expected_response": status.HTTP_403_FORBIDDEN
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": [str(other_cost_models[0])]
                    }
                },
                "expected_response": status.HTTP_403_FORBIDDEN,
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": ["*"]
                    }
                },
                "expected_response": status.HTTP_200_OK,
                "value": round(Decimal(random.random()), 6),
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": [str(cost_model_uuid)]
                    }
                },
                "expected_response": status.HTTP_200_OK,
                "value": round(Decimal(random.random()), 6),
            },
        ]
        client = APIClient()

        for test_case in test_matrix:
            with patch.object(RbacService,
                              "get_access_for_user",
                              return_value=test_case.get("access")):
                url = reverse("costmodels-list")
                rate_data = copy.deepcopy(self.fake_data)
                rate_data["rates"][0].get(
                    "tiered_rates")[0]["value"] = test_case.get("value")

                url = reverse("costmodels-detail",
                              kwargs={"uuid": cost_model_uuid})
                caches["rbac"].clear()
                response = client.put(url,
                                      data=rate_data,
                                      format="json",
                                      **request_context["request"].META)

                self.assertEqual(response.status_code,
                                 test_case.get("expected_response"))

        # DELETE tests
        test_matrix = [
            {
                "access": {
                    "rate": {
                        "read": [],
                        "write": []
                    }
                },
                "expected_response": status.HTTP_403_FORBIDDEN,
                "cost_model_uuid": cost_model_uuid,
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": [str(other_cost_models[0])]
                    }
                },
                "expected_response": status.HTTP_403_FORBIDDEN,
                "cost_model_uuid": cost_model_uuid,
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": ["*"]
                    }
                },
                "expected_response": status.HTTP_204_NO_CONTENT,
                "cost_model_uuid": cost_model_uuid,
            },
            {
                "access": {
                    "rate": {
                        "read": ["*"],
                        "write": [str(other_cost_models[0])]
                    }
                },
                "expected_response": status.HTTP_204_NO_CONTENT,
                "cost_model_uuid": other_cost_models[0],
            },
        ]
        client = APIClient()
        for test_case in test_matrix:
            with patch.object(RbacService,
                              "get_access_for_user",
                              return_value=test_case.get("access")):
                url = reverse(
                    "costmodels-detail",
                    kwargs={"uuid": test_case.get("cost_model_uuid")})
                caches["rbac"].clear()
                response = client.delete(url,
                                         **request_context["request"].META)
                self.assertEqual(response.status_code,
                                 test_case.get("expected_response"))
Exemple #38
0
 def test_delete_cost_model_invalid(self):
     """Test that deleting an invalid cost model returns an error."""
     url = reverse("costmodels-detail", kwargs={"uuid": uuid4()})
     client = APIClient()
     response = client.delete(url, **self.headers)
     self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Exemple #39
0
class TweetTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username='******', 
            password='******'  
        )
        
        self.user2 = User.objects.create_user(
            username='******', 
            password='******'
        )

        self.client = APIClient()
        self.client2 = APIClient()

        self.client.login(
            username=self.user.username, 
            password='******'
        )

        self.client2.login(
            username=self.user2.username, 
            password='******'
        )

        self.tweet1 = Tweet.objects.create(
            content = 'content 1', 
            user = self.user
        )

        self.tweet2 = Tweet.objects.create(
            content = 'content 2', 
            user = self.user
        )

        self.tweet3 = Tweet.objects.create(
            content = 'content 3', 
            user = self.user
        )

    def test_tweets_created(self):
        self.assertEqual(self.tweet1.id, 1)
        self.assertEqual(self.tweet2.id, 2)
        self.assertEqual(self.tweet3.id, 3)

    def test_tweet_list_api(self):
        response = self.client.get('/api/tweets/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.json()), 3)

    def test_action_like_api(self):
        response = self.client.post('/api/tweets/1/like')
        self.assertEqual(response.status_code, 200)

    # def test_action_retweet_api(self):
    #     response = self.client.post('/api/tweets/1/retweet')
    #     self.assertEqual(response.status_code, 201)
    #     self.assertEqual(
    #         Tweet.objects.get(id=4).retweet.content,
    #         Tweet.objects.get(id=1).content
    #     )

    def test_tweet_create_api(self):
        response = self.client.post(
            '/api/tweets/create',
            data={
                'content': 'This is a new tweet'
            }    
        )

        self.assertEqual(response.status_code, 201)
        self.assertEqual(
            Tweet.objects.get(id=4).content,
            'This is a new tweet'
        )

    def test_tweet_multiple_likes(self):
        self.client.post('/api/tweets/1/like')
        self.client2.post('/api/tweets/1/like')
        response = self.client.get('/api/tweets/1')
        self.assertEqual(response.json()['likes'], 2)


    def test_tweet_delete_api(self):
        response = self.client2.delete('/api/tweets/1/delete')
        self.assertEqual(response.status_code, 401)
        response = self.client.delete('/api/tweets/1/delete')
        self.assertEqual(response.status_code, 200)
        response = self.client.delete('/api/tweets/1/delete')
        self.assertEqual(response.status_code, 404)
Exemple #40
0
class TestMovieRetrieveDestroyView(TestCase):
    def setUp(self):
        self.client = APIClient()

        self.user_data = {
            "username": "******",
            "first_name": "Edward",
            "last_name": "Stewart",
            "password": "******",
            "is_staff": False,
            "is_superuser": False,
        }

        self.user_login_data = {"username": "******", "password": "******"}

        self.critic_data = {
            "username": "******",
            "first_name": "Erick",
            "last_name": "Jacquin",
            "password": "******",
            "is_staff": True,
            "is_superuser": False,
        }

        self.critic_login_data = {"username": "******", "password": "******"}

        self.admin_data = {
            "username": "******",
            "first_name": "Jeff",
            "last_name": "Bezos",
            "password": "******",
            "is_staff": True,
            "is_superuser": True,
        }

        self.admin_login_data = {"username": "******", "password": "******"}

        self.movie_data = {
            "title":
            "O Poderoso Chefão",
            "duration":
            "175m",
            "genres": [{
                "name": "Crime"
            }, {
                "name": "Drama"
            }],
            "launch":
            "1972-09-10",
            "classification":
            14,
            "synopsis":
            "Don Vito Corleone (Marlon Brando) é o chefe de uma 'família' de Nova York que está feliz, pois Connie (Talia Shire), sua filha,se casou com Carlo (Gianni Russo). Por ser seu padrinho Vito foi procurar o líder da banda e ofereceu 10 mil dólares para deixar Johnny sair, mas teve o pedido recusado.",
        }

        self.movie_data_2 = {
            "title":
            "Um Sonho de liberdade",
            "duration":
            "142m",
            "genres": [{
                "name": "Ficção Científica"
            }, {
                "name": "Drama"
            }],
            "launch":
            "1994-10-14",
            "classification":
            14,
            "synopsis":
            "Andy Dufresne é condenado a duas prisões perpétuas consecutivas pelas mortes de sua esposa e de seu amante. Porém, só Andy sabe que ele não cometeu os crimes. No presídio, durante dezenove anos, ele faz amizade com Red, sofre as brutalidades da vida na cadeia, se adapta, ajuda os carcereiros, etc.",
        }

        self.movie_data_3 = {
            "title":
            "Em busca de liberdade",
            "duration":
            "175m",
            "genres": [{
                "name": "Obra de época"
            }, {
                "name": "Drama"
            }],
            "launch":
            "2018-02-22",
            "classification":
            14,
            "synopsis":
            "Representando a Grã-Bretanha,  corredor Eric Liddell (Joseph Fiennes) ganha uma medalha de ouro nas Olimpíadas de Paris em 1924. Ele decide ir até a China para trabalhar como missionário e acaba encontrando um país em guerra. Com a invasão japonesa no território chinês durante a Segunda Guerra Mundial, Liddell acaba em um campo de concentração.",
        }

    def test_anonymous_can_filter_movies(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create 3 movies
        self.client.post("/api/movies/", self.movie_data, format="json")
        self.client.post("/api/movies/", self.movie_data_2, format="json")
        self.client.post("/api/movies/", self.movie_data_3, format="json")

        # reset client -> no login
        client = APIClient()

        # filter movie 1
        movies_filter = client.get("/api/movies/1/", format="json")
        self.assertEqual(movies_filter.status_code, 200)
        self.assertEqual(movies_filter.json()["id"], 1)

    def test_anonymous_cannot_filter_movies_with_the_invalid_movie_id(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create 3 movies
        self.client.post("/api/movies/", self.movie_data, format="json")
        self.client.post("/api/movies/", self.movie_data_2, format="json")
        self.client.post("/api/movies/", self.movie_data_3, format="json")

        # reset client -> no login
        client = APIClient()

        # filter movie 99
        movies_filter = client.get("/api/movies/99/", format="json")
        self.assertEqual(movies_filter.status_code, 404)
        self.assertEqual(movies_filter.json(), {"detail": "Not found."})

    def test_user_or_critic_cannot_delete_movies(self):
        # create critic user
        self.client.post("/api/accounts/", self.critic_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.critic_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # critic cannot delete movie
        status_code = self.client.delete("/api/movies/1/",
                                         format="json").status_code
        self.assertEqual(status_code, 403)

        # create user
        self.client.post("/api/accounts/", self.user_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.user_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # user cannot delete movie
        status_code = self.client.delete("/api/movies/1/",
                                         format="json").status_code
        self.assertEqual(status_code, 403)

    def test_anonymous_cannot_delete_movies(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie
        movie = self.client.post("/api/movies/",
                                 self.movie_data,
                                 format="json")

        # reset client -> no login
        client = APIClient()

        # delete movie
        movie_delete = client.delete("/api/movies/1/", format="json")
        self.assertEqual(movie_delete.status_code, 401)
        self.assertEqual(
            movie_delete.json(),
            {"detail": "Authentication credentials were not provided."},
        )

    def test_admin_can_delete_movie(self):
        # create admin user
        self.client.post("/api/accounts/", self.admin_data, format="json")

        # login
        token = self.client.post("/api/login/",
                                 self.admin_login_data,
                                 format="json").json()["token"]

        self.client.credentials(HTTP_AUTHORIZATION="Token " + token)

        # create movie
        movie = self.client.post("/api/movies/",
                                 self.movie_data,
                                 format="json")

        # get movies
        movies = self.client.get("/api/movies/", format="json")
        self.assertEqual(len(movies.json()), 1)

        # delete movie
        status_code = self.client.delete("/api/movies/1/",
                                         format="json").status_code
        self.assertEqual(status_code, 204)

        # get movies
        movies = self.client.get("/api/movies/", format="json")
        self.assertEqual(len(movies.json()), 0)
        self.assertEqual(movies.json(), [])
Exemple #41
0
class ViewTestCase(TestCase):
    """Test suite for the API views."""
    def setUp(self):
        """Define the test client and other variables."""
        user = User.objects.create(username="******")

        # Initialize client and force it to use authentication
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        self.complaint_data = {
            'category': 'Street Noise',
            'severity': '5',
            'latitude': 55.6786513,
            'longitude': 12.5693486,
            'owner': user.id
        }
        self.response = self.client.post(reverse('create'),
                                         self.complaint_data,
                                         format="json")

    def test_authorization_is_enforced(self):
        """Test that the api has user authorization."""
        new_client = APIClient()
        res = new_client.get('/complaints/', kwargs={'pk': 3}, format="json")
        self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)

    def test_api_can_create_a_complaint(self):
        """Test the api has complaint creation capability."""
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    def test_api_can_get_a_complaint(self):
        """Test the api can get a given complaint."""
        complaint = Complaint.objects.get(id=1)
        res = self.client.get('/complaints/',
                              kwargs={'pk': complaint.id},
                              format="json")

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertContains(res, complaint)

    def test_api_can_update_a_complaint(self):
        """Test the api can update a given complaint."""
        """Note from Chad: I don't think the actual API should be able to do this."""
        complaint = Complaint.objects.get()
        change_complaint = {
            'comments': 'Business Noise',
            'severity': self.complaint_data['severity'],
            'latitude': self.complaint_data['latitude'],
            'longitude': self.complaint_data['longitude']
        }
        res = self.client.put(reverse('details', kwargs={'pk': complaint.id}),
                              change_complaint,
                              format='json')
        print(res)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_api_can_delete_complaint(self):
        """Test the api can delete a bucketlist."""
        complaint = Complaint.objects.get()
        res = self.client.delete(reverse('details',
                                         kwargs={'pk': complaint.id}),
                                 format='json',
                                 follow=True)

        self.assertEquals(res.status_code, status.HTTP_204_NO_CONTENT)
class cultural_heritage_item(TestCase):
    def setUp(self):
        self.email = '*****@*****.**'
        self.username = '******'
        self.password = '******'
        self.login_url = '/api/auth/login/'
        self.sigun_url = '/api/auth/signup/'
        self.cultural_heritage_item_url = '/cultural_heritage_item/'
        self.tags_url = '/tags/'
        self.my_items_url = '/cultural_heritage_item/myitems'
        self.user = Account.objects.create_user(
            email=self.email, password=self.password, username=self.username)

        self.email2 = '*****@*****.**'
        self.username2 = 'heisenberg13'
        self.password2 = 'passworD1ss'
        self.cultural_heritage_item_url = '/cultural_heritage_item/'
        self.user2 = Account.objects.create_user(email="*****@*****.**", username="******",
                                                 password="******")
        self.data = {
            'username': self.username,
            'email': self.email,
            'password': self.password,
            'confirm_password': self.password,
        }
        self.client = APIClient()
        self.client.login(username=self.username, password=self.password)

        self.client2 = APIClient()
        self.client2.login(username="******", password="******")

    def test_cultural_heritage_favorite_item(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response_content = json.loads(smart_text(response.content))
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )

        self.assertEqual(response.status_code, 201)

    def test_get_favorite_items(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response.status_code, 201)
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        item_data = {
            "title": "Urgot top montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response_content = json.loads(smart_text(response.content))
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response = self.client.get(
            '/user/cultural_heritage_item/favorite/',
            format='json',
        )
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response_content['results']), 2)
        self.assertEqual(response_content['results'][0]['title'], 'Ahri mid montage')

    def test_get_favorited_cultural_heritage_item(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response = self.client.get(
            self.cultural_heritage_item_url + str(id),
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response_content['is_favorite'], True)

        response = self.client.get(
            self.cultural_heritage_item_url,
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertAlmostEqual(response_content['results'][0]['is_favorite'], True)

    def test_unfavorite_cultural_heritage_item(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response = self.client.delete(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 204)
        response = self.client.get(
            self.cultural_heritage_item_url + str(id),
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response_content['is_favorite'], False)

    def test_cultural_heritage_item_favorited_amount(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)

        response = self.client2.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 201)
        response = self.client.get(
            self.cultural_heritage_item_url + str(id),
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response_content['favorited_amount'], 2)

    def test_favorite_cultural_heritage_item_twice(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        # Here we ensure that the same user cannot favorite the same item more than once.
        response = self.client.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        self.assertEqual(response.status_code, 400)

    def test_cultural_heritage_item_favorited_amount_field_not_editable(self):
        item_data = {
            "title": "Ahri mid montage",
            "favorited_amonut": 10,
        }
        response = self.client.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        response = self.client.get(
            self.cultural_heritage_item_url + str(id),
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response_content['favorited_amount'], 0)

    def test_get_favorited_cultural_heritage_item_favorited_by_another_user(self):
        item_data = {
            "title": "Ahri mid montage",
        }
        response = self.client2.post(
            self.cultural_heritage_item_url,
            item_data,
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        id = response_content['id']
        self.assertEqual(response.status_code, 201)
        response = self.client2.post(
            '/user/cultural_heritage_item/' + str(response_content['id']) + '/favorite/',
            format='json',

        )
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response.status_code, 201)
        response = self.client.get(
            self.cultural_heritage_item_url + str(id),
            format='json',

        )
        self.assertEqual(response.status_code, 200)
        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response_content['is_favorite'], False)

        response = self.client.get(
            self.cultural_heritage_item_url,
            format='json',

        )

        response_content = json.loads(smart_text(response.content))
        self.assertEqual(response.status_code, 200)
        self.assertAlmostEqual(response_content['results'][0]['is_favorite'], False)
Exemple #43
0
    def test_unmapped_comment_requests(self):
        client = APIClient()
        # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        # client.credentials(HTTP_AUTHORIZATION='Token testtesttest123')

        # client.login(username='******', password='******')

        # client.session.auth = HTTPBasicAuth('testtesttest123', 'check')

        # print("\nUSERS:", AAPUser.objects.all().values())
        # user = AAPUser.objects.filter(elixir_id='testtesttest123')
        # print("\nUSER:"******"\nFORCE AUTH")

        # View comment - unmapped.AddGetComments
        response = client.get('/unmapped/2/comments/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['comments'], [])

        # Add a comment - unmapped.AddGetComments
        response = client.post(
            '/unmapped/2/comments/',
            data={
                'text': 'This is a test comment'
            }
        )
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['id'], 1)

        # View a comment - unmapped.AddGetComments
        response = client.get('/unmapped/2/comments/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['comments'][0]['text'], 'This is a test comment')
        self.assertEqual(response.data['comments'][0]['user'], 'Zapp Brannigan')

        # Edit a comment - unmapped.EditDeleteComment
        response = client.put(
            '/unmapped/2/comments/1/',
            data={
                'text': 'This is a changed comment'
            }
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['commentId'], 1)

        # View a comment - unmapped.AddGetComments
        response = client.get('/unmapped/2/comments/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.data['comments'][0]['text'],
            'This is a changed comment'
        )
        self.assertEqual(
            response.data['comments'][0]['user'],
            'Zapp Brannigan'
        )

        response = client.put(
            '/unmapped/2/comments/1/',
            data={}
        )
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['error'], 'Text not specified')

        response = client.put(
            '/unmapped/2/comments/99/',
            data={
                'text': 'Editing a non-existent comment'
            }
        )
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['error'], 'Invalid comment ID: 99')

        # Delete a comment - unmapped.EditDeleteComment
        response = client.delete('/unmapped/2/comments/1/')
        self.assertEqual(response.status_code, 204)
        self.assertEqual(response.data, None)

        response = client.delete('/unmapped/2/comments/99/')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['error'], 'Invalid comment ID: 99')

        # View comment - mappings.MappingCommentsView
        response = client.get('/unmapped/2/comments/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['comments'], [])

        # Edit a deleted comment - unmapped.EditDeleteComment
        response = client.put(
            '/unmapped/2/comments/1/',
            data={
                'text': 'This is not possible'
            }
        )
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['error'], 'Cannot edit deleted comment')
Exemple #44
0
class PrivateProductsApiTests(TestCase):
    """Test the authorized user products API"""

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            '*****@*****.**',
            'test123'
        )
        self.client = APIClient()
        self.client.force_authenticate(self.user)

    def test_retrieve_product_categories(self):
        """Test retrieving products"""
        # test_key = ProductCategory.objects. 
        ProductCategory.objects.create(name="test name", description="new name")
        test_key = ProductCategory.objects.values()[0]
        # print(test_key.get('id'))
        Product.objects.create(product_category_id=test_key.get('id'), name='Test Product Category #1', description='Test Description #1', unit_price=12, quantity=15)
        Product.objects.create(product_category_id=test_key.get('id'), name='Test Product Category #2', description='Test Description #1', unit_price=12, quantity=15)

        # product_categories = ProductCategory.objects.all().order_by('-name')
        # serializer = ProductCategorySerializer(product_categories, many=True)
        res = self.client.get(PRODUCTS_LIST_URL)

        products = Product.objects.all().order_by('-name')
        serializer = ProductSerializer(products, many=False)

        # print(res.data)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        # self.assertDictEqual(dict(res.data), dict(serializer.data))
    
    def test_create_product_successful(self):
        """Test creating a new product category"""
        
        ProductCategory.objects.create(name="test name", description="new name")
        test_key = ProductCategory.objects.values()[0]
        # print(test_key)
        payload = {
            'name': 'Test Tag',
            'product_category_id': test_key.get('id'),
            'unit_price': 100,
            'quantity': 12,
            'description': 'Test description'
        }
        
        res = self.client.post(PRODUCT_ADD_URL, payload)

        # print(res.data)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)

    def test_get_product_detail(self):
        """Test viewing a product detail"""
        ProductCategory.objects.create(name='Test Product Category #1', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #2', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #3', description='Test Description #1')
        test_key = ProductCategory.objects.values()[1].get('id')
        
        Product.objects.create(product_category_id=test_key, name='Test Product Category #1', description='Test Description #1', unit_price=12, quantity=15)
        pk = Product.objects.values()[0].get('id')

        PRODUCTS_DETAIL_URL = reverse('product:product_details', args=(pk,))
        res = self.client.get(PRODUCTS_DETAIL_URL)
        # print(res.data)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        
    def test_update_product_successful(self):
        ProductCategory.objects.create(name='Test Product Category #1', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #2', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #3', description='Test Description #1')
        test_key = ProductCategory.objects.values()[1].get('id')

        Product.objects.create(product_category_id=test_key, name='Test Product Category #1', description='Test Description #124', unit_price=12, quantity=15)
        pk = Product.objects.values()[0].get('id')

        payload = {
            'name': 'testtt12312321t',
            'description': '123123111111'
        }
        PRODUCTS_EDIT_URL = reverse('product:product_edit', args=(pk,))
        res = self.client.patch(PRODUCTS_EDIT_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)

    def test_update_product_deleted_successfully(self):
        ProductCategory.objects.create(name='Test Product Category #1', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #2', description='Test Description #1')
        ProductCategory.objects.create(name='Test Product Category #3', description='Test Description #1')
        test_key = ProductCategory.objects.values()[1].get('id')

        Product.objects.create(product_category_id=test_key, name='Test Product Category #1', description='Test Description #124', unit_price=12, quantity=15)
        pk = Product.objects.values()[0].get('id')

        PRODUCT_DELETE_URL = reverse('product:product_delete', args=(pk,))
        res = self.client.delete(PRODUCT_DELETE_URL)
        # print(Product.objects.values())
        self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)


    # def test_create_tag_invalid(self):
    #     """Test creating a new product category with invalid payload"""
    #     payload = {'name': 123}
    #     res = self.client.post(PRODUCT_CATEGORY_ADD_URL, payload)

    #     self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Exemple #45
0
class AppTestCase(TestCase):
    """ API tests """
    fixtures = (
        'comments.json',
        'comment-tones.json',
    )

    def setUp(self):
        self.client = APIClient()

    def _test_first_comment(self, comment):
        """ Test the provided comment matches the content of the first comment from the fixtures """
        self.assertIn('url', comment)
        self.assertEqual(comment['url'], 'http://testserver/api/1/')

        self.assertIn('sku', comment)
        self.assertEqual(comment['sku'], 'TEST0001')

        self.assertIn('content', comment)
        self.assertEqual(comment['content'],
                         'I really love this product, it\'s the best!')

        self.assertIn('tone', comment)
        self.assertEqual(comment['tone'], 'joy')

    def test_comment_list(self):
        """ Test comments list"""

        # Perform request
        response = self.client.get('/api/', format='json')
        self.assertEqual(response.status_code, 200)
        data = response.json()

        # Check the correct total number of results are returned
        self.assertIn('count', data)
        self.assertEqual(data['count'], 15)

        # Check the returned results list is correct
        self.assertIn('results', data)
        self.assertIsInstance(data['results'], list)
        self.assertEqual(len(data['results']),
                         settings.REST_FRAMEWORK['PAGE_SIZE'])

        # Check the first returned comment is correct
        self._test_first_comment(data['results'][0])

    def test_comment_retrieve(self):
        """ Test comment retrieval """

        # Perform request that should succeed
        response = self.client.get('/api/1/', format='json')
        self.assertEqual(response.status_code, 200)
        data = response.json()

        # Check the returned comment is correct
        self._test_first_comment(data)

        # Perform request that should fail
        response = self.client.get('/api/9999/', format='json')
        self.assertEqual(response.status_code, 404)

    @patch('comments.api.tasks.fetch_tone')
    def test_comment_create(self, mock_task):
        """ Test comment creation """

        # Perform request that should succeed
        response = self.client.post('/api/', {
            'sku': 'TEST1234',
            'content': 'Test 1234'
        },
                                    format='json')
        self.assertEqual(response.status_code, 201)
        data = response.json()

        # Check the returned comment is correct
        self.assertIn('sku', data)
        self.assertEqual(data['sku'], 'TEST1234')

        self.assertIn('content', data)
        self.assertEqual(data['content'], 'Test 1234')

        self.assertIn('tone', data)
        self.assertIsNone(data['tone'])

        # Perform request that should fail
        response = self.client.post('/api/', {
            'sku': 'SKUTHATISTOOLONG',
            'content': ''
        },
                                    format='json')
        self.assertEqual(response.status_code, 400)
        data = response.json()

        # Check validation errors
        self.assertIn('sku', data)
        self.assertListEqual(
            data['sku'], ['Ensure this field has no more than 8 characters.'])

        self.assertIn('content', data)
        self.assertListEqual(data['content'], ['This field may not be blank.'])

    @patch('comments.api.tasks.fetch_tone')
    def test_comment_update(self, mock_task):
        """ Test comment updating """

        # Perform request that should succeed
        response = self.client.put('/api/1/', {
            'sku': 'TEST1234',
            'content': 'Test 1234'
        },
                                   format='json')
        self.assertEqual(response.status_code, 200)
        data = response.json()

        # Check the returned comment is correct
        self.assertIn('sku', data)
        self.assertEqual(data['sku'], 'TEST1234')

        self.assertIn('content', data)
        self.assertEqual(data['content'], 'Test 1234')

        # Perform request that should fail
        response = self.client.put('/api/1/', {
            'sku': 'SKUTHATISTOOLONG',
            'content': ''
        },
                                   format='json')
        self.assertEqual(response.status_code, 400)
        data = response.json()

        # Check validation errors
        self.assertIn('sku', data)
        self.assertListEqual(
            data['sku'], ['Ensure this field has no more than 8 characters.'])

        self.assertIn('content', data)
        self.assertListEqual(data['content'], ['This field may not be blank.'])

    def test_comment_delete(self):
        """ Test comment deletion """

        # Perform request that should succeed
        response = self.client.delete('/api/1/', format='json')
        self.assertEqual(response.status_code, 204)

        # Perform request that should fail
        response = self.client.put('/api/9999/', format='json')
        self.assertEqual(response.status_code, 404)

    @patch('comments.api.tasks.logger')
    def test_comment_tone_unknown(self, mock_logger):
        """ Test comment tone creation for an unknown comment object """
        fetch_tone(9999)
        mock_logger.error.assert_called_with(
            'Unknown comment object in fetch tone task: 9999')

    @patch('requests.get', side_effect=requests.exceptions.HTTPError())
    @patch('comments.api.tasks.logger')
    def test_comment_tone_request_failure(self, mock_logger, mock_requests):
        """ Test comment tone request failure """
        fetch_tone(1)
        mock_logger.error.assert_called_with(
            'Error response received from Watson API: ')

    @patch('requests.get', side_effect=requests.exceptions.RequestException())
    @patch('comments.api.tasks.logger')
    def test_comment_tone_request_connection_failure(self, mock_logger,
                                                     mock_requests):
        """ Test comment tone request connection failure """
        fetch_tone(1)
        mock_logger.error.assert_called_with(
            'Error requesting from Watson API: ')

    @patch('requests.get')
    @patch('comments.api.tasks.logger')
    def test_comment_tone(self, mock_logger, mock_requests):
        """ Test comment tone creation """
        mock_requests.return_value.json.return_value = {
            "document_tone": {
                "tone_categories": [{
                    "tones": [{
                        "score": 0.24748,
                        "tone_id": "anger"
                    }, {
                        "score": 0.322559,
                        "tone_id": "disgust"
                    }, {
                        "score": 0.108639,
                        "tone_id": "fear"
                    }, {
                        "score": 0.105358,
                        "tone_id": "joy"
                    }, {
                        "score": 0.083174,
                        "tone_id": "sadness"
                    }],
                    "category_id":
                    "emotion_tone",
                }]
            }
        }

        # Check fetch tone task succeeds
        fetch_tone(1)
        mock_logger.error.assert_not_called()

        # Perform request that should succeed
        response = self.client.get('/api/1/', format='json')
        self.assertEqual(response.status_code, 200)
        data = response.json()

        # Check the returned tone is correct
        self.assertIn('tone', data)
        self.assertEqual(data['tone'], 'disgust')
Exemple #46
0
class TransactionViewTestCase(TestCase):
    """Test suite for the api Transaction views."""
    def setUp(self):
        """Define the test client and other test variables."""
        user = User.objects.create_user(username="******")

        # Initialize client and force it to use authentication
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        # Create a new account.
        self.account = Account(name="Dummy Account123")
        self.account.save()

        # Create new category.
        self.category = Category(name="Dummy category123")
        self.category.save()

        # Create new transactionstatus.
        self.transactionstatus = TransactionStatus(name="Dummy status 123")
        self.transactionstatus.save()

        self.data = {
            'transaction_date': time.strftime('%Y-%m-%dT%H:%M:%S'),
            'original_description': 'Dummy Transaction1',
            'account': self.account.id,
            'category': self.category.id,
            'transactionstatus': self.transactionstatus.id
        }

        self.response = self.client.post(reverse('transaction-list'),
                                         self.data,
                                         format="json")

    def test_api_can_create_transaction(self):
        """Test the api has transaction creation capability."""
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    def test_authorization_is_enforced(self):
        """Test that the api has user authorization."""
        new_client = APIClient()
        response = new_client.get(reverse('transaction-detail',
                                          kwargs={'pk': 3}),
                                  format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_api_can_get_transaction(self):
        """Test the api can get a given transaction."""
        transaction = Transaction.objects.get()
        response = self.client.get(reverse('transaction-detail',
                                           kwargs={'pk': transaction.id}),
                                   format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, transaction)

    def test_api_can_update_transaction(self):
        """Test the api can update a given transaction."""
        transaction = Transaction.objects.get()
        change_transaction = {
            'transaction_date': transaction.transaction_date,
            'original_description': 'Changed Transaction Desc',
            'account': self.account.id,
            'category': self.category.id,
            'transactionstatus': self.transactionstatus.id
        }
        res = self.client.put(reverse('transaction-detail',
                                      kwargs={'pk': transaction.id}),
                              change_transaction,
                              format='json')
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_api_can_delete_transaction(self):
        """Test the api can delete a transaction."""
        transaction = Transaction.objects.get()
        response = self.client.delete(reverse('transaction-detail',
                                              kwargs={'pk': transaction.id}),
                                      format='json',
                                      follow=True)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #47
0
 def delete_with_token(self, url, access_token):
     client = APIClient()
     client.credentials(HTTP_AUTHORIZATION='Bearer {}'.format(access_token))
     response = client.delete(url, data={'format': 'json'})
     return response
class UsersIdTests(APITestCase):
    @classmethod
    def setUpClass(cls):
        super(UsersIdTests, cls).setUpClass()
        cls.org = models.Organization.objects.create(name="random_university")
        models.Domain.objects.create(name="mailinator.com",
                                     organization_id=cls.org.id)
        models.AcademicField.objects.create(name="random_field")
        models.AcademicLevel.objects.create(name="random_level")
        cls.user_attrs = [
            'id', 'url', 'email', 'first_name', 'last_name', 'is_active',
            'phone', 'other_phone', 'is_superuser', 'is_staff', 'university',
            'last_login', 'date_joined', 'academic_level', 'academic_field',
            'gender', 'language', 'birthdate', 'groups', 'user_permissions',
            'tickets', 'membership', 'membership_end', 'city',
            'personnal_restrictions', 'academic_program_code', 'faculty',
            'student_number', 'volunteer_for_workplace', 'hide_newsletter',
            'is_in_newsletter', 'number_of_free_virtual_retreat',
            'membership_end_notification'
        ]

    def setUp(self):
        self.client = APIClient()

        self.user = UserFactory()
        self.user.set_password('Test123!')
        self.user.save()

        self.admin = AdminFactory()
        self.admin.set_password('Test123!')
        self.admin.save()

        self.membership = Membership.objects.create(
            name="basic_membership",
            details="1-Year student membership",
            available=True,
            price=50,
            duration=timedelta(days=365),
        )

    def test_retrieve_user_id_not_exist(self):
        """
        Ensure we can't retrieve a user that doesn't exist.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.get(reverse(
            'user-detail',
            kwargs={'pk': 999},
        ))

        content = {"detail": "Not found."}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_retrieve_user_id_not_exist_without_permission(self):
        """
        Ensure we can't know a user doesn't exist without permission
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse(
            'user-detail',
            kwargs={'pk': 999},
        ))

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_retrieve_user(self):
        """
        Ensure we can retrieve a user.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ))

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_retrieve_user_profile(self):
        """
        Ensure we can retrieve our details through /profile.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.get(reverse('profile', ))

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_partial_update_user_with_permission(self):
        """
        Ensure we can update a specific user if caller has permission.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        # Check the status code
        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        content = json.loads(response.content)

        # Check if update was successful
        self.assertEqual(content['phone'], data['phone'])

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

    def test_partial_update_membership(self):
        """
        Ensure we can update a specific user if caller has permission.
        """

        if self.user.membership_end:
            before_membership_end = self.user.membership_end.isoformat()
        else:
            before_membership_end = 'None'

        data = {
            "membership_end": timezone.now().date().isoformat(),
            "membership": reverse('membership-detail',
                                  args=[self.membership.id]),
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        # Check the status code
        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        content = json.loads(response.content)

        # Check if membership didn't not change
        self.assertNotEqual(content['membership_end'], data['membership_end'])
        self.assertNotEqual(content['membership_end'], before_membership_end)

        # Check if membership didn't change
        self.assertNotEqual(content['membership'], data['membership'])
        self.assertIsNone(self.user.membership)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

    def test_partial_update_user_with_permission_change_password(self):
        """
        Ensure we can change password if current password is provided and the
        new password is validated.
        """

        data = {"password": "******", "new_password": "******"}

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        self.user.refresh_from_db()

        # Ensure that the password has been changed successfully
        self.assertTrue(self.user.check_password("!321tseT"))

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @override_settings(
        LOCAL_SETTINGS={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "EMAIL_CHANGE_CONFIRMATION": "test",
            }
        })
    def test_partial_update_user_change_email(self):
        """
        Ensure we can get an activation email at a new email address if its
        domain matches with the current university.
        """
        data = {"email": "*****@*****.**"}

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        old_email = self.user.email

        self.user.refresh_from_db()

        # Ensure that the email was not changed yet
        self.assertEqual(self.user.email, old_email)

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # An email with an activation token is sent
        self.assertEqual(len(mail.outbox), 1)

    def test_partial_update_user_change_email_invalid_domain(self):
        """
        Ensure we can't change email address if its domain does not match with
        the current university.
        """
        data = {"email": "*****@*****.**"}

        self.user.university = self.org
        self.user.save()

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'email': ['Invalid domain name.']}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_partial_update_user_change_university(self):
        """
        Ensure we can change university if the current email domain matches.
        """
        data = {
            "university": {
                'name': "Blitz",
            }
        }

        new_uni = models.Organization.objects.create(name="Blitz")
        models.Domain.objects.create(name="blitz.com",
                                     organization_id=new_uni.id)

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        self.user.refresh_from_db()

        # Ensure that university was updated
        self.assertEqual(self.user.university, new_uni)

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # No email is sent if only the university changed
        self.assertEqual(len(mail.outbox), 0)

    def test_partial_update_user_change_university_invalid_domain(self):
        """
        Ensure we can't change university if the current email domain does not
        match.
        """
        data = {"university": {'name': self.org.name}}

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'email': ['Invalid domain name.']}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @override_settings(
        LOCAL_SETTINGS={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "EMAIL_CHANGE_CONFIRMATION": "test",
            }
        })
    def test_partial_update_user_change_university_and_email(self):
        """
        Ensure we can get an activation email at a new email address if its
        domain matches with the newly provided university.
        """
        data = {
            "email": "*****@*****.**",
            "university": {
                'name': self.org.name,
            }
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        old_email = self.user.email
        old_university = self.user.university

        self.user.refresh_from_db()

        # Ensure that the email was not changed yet
        self.assertEqual(self.user.email, old_email)

        # Ensure that the university was not changed yet
        self.assertEqual(self.user.university, old_university)

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # An email with an activation token is sent
        self.assertEqual(len(mail.outbox), 1)

    def test_partial_update_user_change_uni_and_email_invalid_domain(self):
        """
        Ensure we can't change email address if its domain does not match with
        the newly provided university.
        """
        data = {
            "email": "*****@*****.**",
            "university": {
                'name': self.org.name
            }
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'email': ['Invalid domain name.']}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_partial_update_user_remove_university(self):
        """
        Ensure we can remove university at all time.
        If the university field is set as NULL, the API interprets this as
        "remove the university".
        """
        data = {"university": None}

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = json.loads(response.content)

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        self.user.refresh_from_db()

        # Ensure that university was updated
        self.assertEqual(self.user.university, None)

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # No email is sent if only the university changed
        self.assertEqual(len(mail.outbox), 0)

    @override_settings(
        LOCAL_SETTINGS={
            "EMAIL_SERVICE": True,
            "FRONTEND_INTEGRATION": {
                "EMAIL_CHANGE_CONFIRMATION": "test",
            }
        })
    def test_update_user_with_permission(self):
        """
        Ensure we can update a specific user if caller has permission.
        Put requires a full update, including password and email.
        """
        data = {
            'email': "*****@*****.**",
            'password': '******',
            'new_password': '******',
            'phone': '1234567890',
            'first_name': 'Chuck',
            'last_name': 'Norris',
            'university': {
                'name': "random_university"
            },
            'academic_field': {
                'name': "random_field"
            },
            'academic_level': {
                'name': "random_level"
            },
            'gender': "M",
            'language': "en",
            'birthdate': "1999-11-11",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.put(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        # Check the status code
        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        content = json.loads(response.content)

        self.user.refresh_from_db()

        # Check if update was successful
        self.assertEqual(content['phone'], data['phone'])
        self.assertEqual(content['language'], data['language'])
        self.assertTrue(self.user.check_password("!321tset"))

        # Check id of the user
        self.assertEqual(content['id'], self.user.id)

        # Check the system doesn't return attributes not expected
        attributes = self.user_attrs.copy()
        for key in content.keys():
            self.assertTrue(
                key in attributes, 'Attribute "{0}" is not expected but is '
                'returned by the system.'.format(key))
            attributes.remove(key)

        # Ensure the system returns all expected attributes
        self.assertTrue(
            len(attributes) == 0, 'The system failed to return some '
            'attributes : {0}'.format(attributes))

        # An email with an activation token is sent to the new email address
        self.assertEqual(len(mail.outbox), 1)

    def test_update_user_without_permission(self):
        """
        Ensure we can't update a specific user doesn't have permission.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.admin.id},
            ),
            data,
            format='json',
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_non_existent_user(self):
        """
        Ensure we get permission denied when trying to update an invalid user.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': 9999},
            ),
            data,
            format='json',
        )

        content = {
            'detail': 'You do not have permission to perform this action.'
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_non_existent_user_as_admin(self):
        """
        Ensure we get not found when trying to update an invalid user as
        an admin.
        """

        data = {
            "phone": "1234567890",
        }

        self.client.force_authenticate(user=self.admin)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': 9999},
            ),
            data,
            format='json',
        )

        content = {'detail': 'Not found.'}

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_user_weak_new_password(self):
        """
        Ensure we can't update our password if it is not validated.
        """

        data = {
            "phone": "1234567890",
            "password": "******",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {
            'new_password': [
                'This password is too common.',
                'This password is entirely numeric.'
            ]
        }
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_missing_old_password(self):
        """
        Ensure we can't update our password if the current one is not provided.
        """

        data = {
            "phone": "1234567890",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'password': '******'}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_wrong_old_password(self):
        """
        Ensure we can't update our password if the current one is wrong.
        """

        data = {
            "phone": "1234567890",
            "password": "******",
            "new_password": "******",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {'password': '******'}
        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_user_invalid_fields(self):
        """
        Ensure we can't update fields with invalid values.
        Some fields like university are ignored and left in data on
        purpose.
        """

        data = {
            'email': '*****@*****.**',
            'password': '******',
            'first_name': 'Chuck',
            'last_name': 'Norris',
            'university': {
                "name": "invalid_university"
            },
            'academic_field': {
                'name': "invalid_field"
            },
            'academic_level': {
                'name': "invalid_level"
            },
            'gender': "invalid_gender",
            'birthdate': "invalid_date",
        }

        self.client.force_authenticate(user=self.user)

        response = self.client.patch(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ),
            data,
            format='json',
        )

        content = {
            'academic_field': ['This academic field does not exist.'],
            'academic_level': ['This academic level does not exist.'],
            'birthdate': [
                'Date has wrong format. Use one of these formats instead: '
                'YYYY-MM-DD.'
            ],
            'gender': ['"invalid_gender" is not a valid choice.'],
            'university': ['This university does not exist.'],
        }

        self.assertEqual(json.loads(response.content), content)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_delete_user_as_admin(self):
        """
        Ensure we can deactivate a user as an admin.
        """
        self.client.force_authenticate(user=self.admin)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ), )
        self.user.refresh_from_db()

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(self.user.is_active)

        self.user.is_active = True
        self.user.refresh_from_db()

    def test_delete_user(self):
        """
        Ensure that a user can deactivate its own account.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': self.user.id},
            ), )
        self.user.refresh_from_db()

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(self.user.is_active)

        self.user.is_active = True
        self.user.refresh_from_db()

    def test_delete_inexistent_user(self):
        """
        Ensure that deleting a non-existent user does nothing.
        """
        self.client.force_authenticate(user=self.user)

        response = self.client.delete(
            reverse(
                'user-detail',
                kwargs={'pk': 999},
            ), )

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #49
0
class PrivatSuppliersApiTests(TestCase):
    """Test the authorized user API"""

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            '*****@*****.**',
            'test123'
        )
        self.client = APIClient()
        self.client.force_authenticate(self.user)

    def test_retrieve_product_categories(self):
        """Test retrieving tags"""
        Supplier.objects.create(name='Test Product Category #1', email='*****@*****.**', address='Test Address #1')
        # ProductCategory.objects.create(name='Test Product Category #2', description='Test Description #2')

        res = self.client.get(SUPPLIERS_LIST_URL, format='json')
        suppliers = Supplier.objects.all()
        serializer = SupplierSerializer(data=suppliers, many=True)
        serializer.is_valid()

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        # self.assertDictEqual(dict(res.data), dict(serializer.data))
    
    def test_create_product_category_successful(self):
        """Test creating a new product category"""
        payload = {
            # 'supplier':{
                'name': 'Test Tag',
                'email': '*****@*****.**',
                'address': 'Test address'
            # }
        }
        
        res = self.client.post(SUPPLIER_ADD_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)

    def test_get_supplier_detail(self):
        """Test viewing a supplier detail"""
        
        Supplier.objects.create(name='Test Supplier #1', email='*****@*****.**', address='Test Address #1')
        pk = Supplier.objects.values()[0].get('id')

        SUPPLIER_DETAIL_URL = reverse('supplier:details', args=(pk,))
        res = self.client.get(SUPPLIER_DETAIL_URL)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        
    def test_update_supplier_successful(self):
        Supplier.objects.create(name='Test Supplier #1', email='*****@*****.**', address='Test Address #1')
        pk = Supplier.objects.values()[0].get('id')

        payload = {
            # 'name': 'testtt12312321t',
            'name': 'good lord'
        }
        SUPPLIER_DETAIL_EDIT_URL = reverse('supplier:edit', args=(pk,))
        res = self.client.patch(SUPPLIER_DETAIL_EDIT_URL, payload)
        
        self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)

    def test_supplier_deleted_successfully(self):
        Supplier.objects.create(name='Test Supplier #1', email='*****@*****.**', address='Test Address #1')
        pk = Supplier.objects.values()[0].get('id')

        SUPPLIER_DETAIL_DELETE_URL = reverse('supplier:delete', args=(pk,))
        res = self.client.delete(SUPPLIER_DETAIL_DELETE_URL)

        self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)
Exemple #50
0
    def test_destroy_requires_authentication(self):
        client = APIClient(HTTP_X_REAL_IP='127.0.0.1')
        url = '/api/image_tagging/{0}/'.format(self.tag1)
        response = client.delete(url, format='json')

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Exemple #51
0
class ProductAppTest(AuthenticationTest, APITestCase):
    def setUp(self):
        self.product = Products.objects.create(
            ProductName='shoe',
            ProductQuantity=2,
            ProductPrice=2.12,
            ProductDescription='Tabriz shoes')
        self.product.save()

        # product management urls:
        self.create_read_url = reverse('product_operation-list')
        self.read_update_delete_url = reverse(
            'product_operation-detail', kwargs={'pk': self.product.ProductId})

        # Products Management reverse urls:
        self.user_create_read_url = reverse('product_list-list')

        # if you want use force authenticate:
        self.me = super().setUp()
        self.client = APIClient()
        self.client.force_authenticate(user=self.me)

        # if want to use by token call use like below:
        # super().test_api_jwt()
        # self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.tkn['access'])

    # client side {fetch products list in clients endpoints}
    def test_user_product_list(self):
        """ render product list for clients
            Method : GET
            Permission : AnyOne
            Authentication : None
        """

        response = self.client.get(self.user_create_read_url)
        self.assertContains(response, self.product.ProductDescription)
        self.assertEquals(response.status_code, status.HTTP_200_OK)

    # Admin side control over products:
    def test_product_list(self):
        """ render products list
            Method : GET
            Permission : IsAdmin
            Authentication : IsAuthenticated
        """
        response = self.client.get(self.create_read_url)
        self.assertContains(response, self.product.ProductDescription)
        self.assertEquals(response.status_code, status.HTTP_200_OK)

    def test_product_create(self):
        """ create new product
            Method : POST
            Permission : IsAdmin
            Authentication : IsAuthenticated

         """

        post = {
            "ProductName": "hat",
            "ProductQuantity": 5,
            "ProductPrice": 2.12,
            "ProductDescription": "fedora hat"
        }

        response = self.client.post(self.create_read_url, post)
        self.assertEquals(response.status_code, 201)
        self.assertEquals(response.data['ProductName'], post['ProductName'])

    def test_product_detail(self):
        """ get product over ProductId as PK
            Method : GET/PK/
            Permission : IsAdmin
            Authentication : IsAuthenticated

        """

        response = self.client.get(self.read_update_delete_url)
        self.assertEquals(response.data['ProductName'],
                          self.product.ProductName)
        self.assertEquals(response.status_code, status.HTTP_200_OK)

    def test_product_update(self):
        """ Update product record over ProductId as PK
            Method : PUT/PK/
            Permission : IsAdmin
            Authentication : IsAuthenticated

        """

        data = {
            "ProductName": "book",
            "ProductQuantity": 8,
            "ProductPrice": 3.12,
            "ProductDescription": "programing book"
        }
        response = self.client.put(self.read_update_delete_url, data=data)
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, data['ProductName'])

    def test_product_partial_update(self):
        """ Particular update product record over ProductId as PK
            Method : PATCH/PK/
            Permission : IsAdmin
            Authentication : IsAuthenticated
        """

        data = {
            "ProductName": "pencil",
        }
        response = self.client.patch(self.read_update_delete_url, data=data)
        self.assertEquals(response.status_code, status.HTTP_200_OK)

    def test_product_delete(self):
        """ Delete product record according ProductId as PK
            Method : DELETE/PK/
            Permission : IsAdmin
            Authentication : IsAuthenticated
        """

        response = self.client.delete(self.read_update_delete_url)
        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertIsNone(response.data)
Exemple #52
0
class ViewTestCase(TestCase):
    """Test suite for the bucketlist api views."""

    def setUp(self):
        """Define the test client and other test variables."""
        user = User(email='*****@*****.**')
        user.save()
        self.client = APIClient()
        self.client.force_authenticate(
            user=user, token=user.token)
        self.bucketlist_data = {
            'name': 'Go to Ibiza',
            'owner': user.id
        }
        self.response = self.client.post(
            reverse('bucket-list'),
            self.bucketlist_data,
            format='json'
        )

    def test_api_can_create_a_bucketlist(self):
        """Test the api has bucket creation capability."""
        self.assertEqual(
            self.response.status_code, status.HTTP_201_CREATED)

    def test_authorization_is_enforced(self):
        """Test that the api has user authorization."""
        new_client = APIClient()
        response = new_client.get(
            '/api/v1/bucketlist/', kwargs={'pk': 3}, format='json')
        self.assertEqual(
            response.status_code, status.HTTP_403_FORBIDDEN)

    def test_api_can_get_a_bucketlist(self):
        """Test the api can get a given bucketlist."""
        bucketlist = Bucketlist.objects.get(id=1)
        response = self.client.get(
            reverse('bucket-detail',
                    kwargs={'pk': bucketlist.id}),
            format='json'
        )
        self.assertEqual(
            response.status_code, status.HTTP_200_OK)
        self.assertContains(response, bucketlist)

    def test_api_can_update_bucketlist(self):
        """Test the api can update a given bucketlist."""
        bucketlist = Bucketlist.objects.get()
        change_bucketlist = {'name': 'Something new'}
        response = self.client.put(
            reverse('bucket-detail',
                    kwargs={'pk': bucketlist.id}),
            change_bucketlist, format='json'
        )
        self.assertEqual(
            response.status_code, status.HTTP_200_OK)

    def test_api_can_delete_bucketlist(self):
        """Test the api can delete a bucketlist."""
        bucketlist = Bucketlist.objects.get()
        response = self.client.delete(
            reverse('bucket-detail',
                    kwargs={'pk': bucketlist.id}),
            format='json',
            follow=True
        )
        self.assertEqual(
            response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #53
0
class VideoURLTestCase(TestCase):
    def setUp(self):
        self.user = UserFactory()
        self.video = VideoFactory()
        self.primary_url = self.video.get_primary_videourl_obj()
        self.other_url = VideoURLFactory(video=self.video)
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
        self.list_url = reverse('api:video-url-list',
                                args=(self.video.video_id, ))

    def detail_url(self, video_url):
        return reverse('api:video-url-detail',
                       kwargs={
                           'video_id': video_url.video.video_id,
                           'pk': video_url.id,
                       },
                       request=APIRequestFactory().get('/'))

    def correct_data(self, video_url):
        return {
            'created': format_datetime_field(video_url.created),
            'url': video_url.url,
            'primary': video_url.primary,
            'original': video_url.original,
            'id': video_url.id,
            'resource_uri': self.detail_url(video_url),
        }

    def test_list_urls(self):
        response = self.client.get(self.list_url)
        assert_equal(response.status_code, status.HTTP_200_OK)
        assert_items_equal(response.data['objects'], [
            self.correct_data(self.primary_url),
            self.correct_data(self.other_url)
        ])

    def test_get_detail(self):
        response = self.client.get(self.detail_url(self.primary_url))
        assert_equal(response.status_code, status.HTTP_200_OK)
        assert_items_equal(response.data, self.correct_data(self.primary_url))

    def test_add_url(self):
        url = 'http://example.com/added-video.mp4'
        response = self.client.post(self.list_url, {'url': url})
        assert_equal(response.status_code, status.HTTP_201_CREATED)
        qs = self.video.videourl_set.filter(url=url)
        assert_equal(qs.count(), 1)
        assert_equal(qs[0].added_by, self.user)

    def check_primary_url(self, url):
        qs = self.video.videourl_set.filter(primary=True)
        assert_equal([vurl.url for vurl in qs], [url])

    def test_add_primary_url(self):
        url = 'http://example.com/added-video.mp4'
        response = self.client.post(self.list_url, {
            'url': url,
            'primary': True
        })
        assert_equal(response.status_code, status.HTTP_201_CREATED)
        self.check_primary_url(url)

    def test_add_with_original(self):
        url = 'http://example.com/added-video.mp4'
        response = self.client.post(self.list_url, {
            'url': url,
            'original': True
        })
        assert_equal(response.status_code, status.HTTP_201_CREATED)
        assert_true(self.video.videourl_set.get(url=url).original)

    def test_set_primary(self):
        response = self.client.put(self.detail_url(self.other_url),
                                   {'primary': True})
        assert_equal(response.status_code, status.HTTP_200_OK,
                     response.content)
        self.check_primary_url(self.other_url.url)

    def test_set_original(self):
        response = self.client.put(self.detail_url(self.other_url),
                                   {'original': True})
        assert_equal(response.status_code, status.HTTP_200_OK,
                     response.content)
        assert_true(test_utils.reload_obj(self.other_url).original)

    def test_delete_url(self):
        response = self.client.delete(self.detail_url(self.other_url))
        assert_equal(response.status_code, status.HTTP_204_NO_CONTENT,
                     response.content)
        assert_equal(list(self.video.videourl_set.all()), [self.primary_url])

    def test_cant_delete_primary_url(self):
        response = self.client.delete(self.detail_url(self.primary_url))
        assert_equal(response.status_code, status.HTTP_400_BAD_REQUEST,
                     response.content)
        assert_items_equal(self.video.videourl_set.all(),
                           [self.primary_url, self.other_url])

    def test_writeable_fields(self):
        response = self.client.options(self.list_url)
        assert_writable_fields(response, 'POST',
                               ['url', 'original', 'primary'])

    def test_writeable_fields_details(self):
        response = self.client.options(self.detail_url(self.primary_url))
        assert_writable_fields(response, 'PUT', ['original', 'primary'])
Exemple #54
0
class PostTests(APITestCase):
    def setUp(self):
        self.client_authentication = APIClient()
        self.client_no_authentication = APIClient()
        self.user = _create_user()
        self.token = Token.objects.create(user=self.user).key
        self.client_authentication.credentials(HTTP_AUTHORIZATION='Token ' +
                                               self.token)

    def test_post_create(self):
        url = reverse('posts-list')
        data = {
            'text': 'test post',
        }
        response = self.client_authentication.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        post = Post.objects.last()
        self.assertEqual(post.text, 'test post')

    def test_posts_list(self):
        url = reverse('posts-list')
        response = self.client_no_authentication.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        response = self.client_authentication.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_posts_retrieve(self):
        post = Post.objects.get_or_create(author=self.user,
                                          text='test post')[0]
        url = reverse('posts-detail', kwargs={'pk': post.id})
        response = self.client_no_authentication.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        response = self.client_authentication.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('text'), post.text)
        self.assertEqual(response.data.get('author'), post.author.username)

    def test_post_update(self):
        post = Post.objects.get_or_create(author=self.user,
                                          text='test post')[0]
        url = reverse('posts-detail', kwargs={'pk': post.id})
        response = self.client_no_authentication.put(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        data = {
            'text': 'test post put',
        }
        response = self.client_authentication.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('text'), data.get('text'))

    def test_post_partial_update(self):
        post = Post.objects.get_or_create(author=self.user,
                                          text='test post')[0]
        url = reverse('posts-detail', kwargs={'pk': post.id})
        response = self.client_no_authentication.patch(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        data = {
            'text': 'test post put',
        }
        response = self.client_authentication.patch(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('text'), data.get('text'))

    def test_post_partial_destroy(self):
        post = Post.objects.get_or_create(author=self.user,
                                          text='test post')[0]
        url = reverse('posts-detail', kwargs={'pk': post.id})
        response = self.client_no_authentication.delete(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        response = self.client_authentication.delete(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Exemple #55
0
class TestUserView(TestCase):
    def setUp(self):
        self.client = APIClient()

    def test_usernames_with_periods(self):
        u = UserFactory(username="******")
        url = reverse("user-detail", args=[u.username])
        res = self.client.get(url)
        eq_(res.status_code, 200)
        eq_(res.data["username"], u.username)

    def test_cant_delete(self):
        p = ProfileFactory()
        self.client.force_authenticate(user=p.user)
        url = reverse("user-detail", args=[p.user.username])
        res = self.client.delete(url)
        eq_(res.status_code, 405)

    def test_weekly_solutions(self):
        eight_days_ago = datetime.now() - timedelta(days=8)
        # First one is a solution, but it is too old.
        # second answer is not a solution.
        SolutionAnswerFactory(created=eight_days_ago)
        AnswerFactory()
        res = self.client.get(reverse("user-weekly-solutions"))
        eq_(res.status_code, 200)
        eq_(len(res.data), 0)

        # Check that the data about the contributors is showing currectly
        user_info_list = [
        ]  # Info list with username and their number of solutions
        top_answer_number = 15
        for i in range(12):
            user = UserFactory()
            SolutionAnswerFactory.create_batch(top_answer_number, creator=user)
            user_info_list.append((user.username, top_answer_number))
            top_answer_number -= 1

        res = self.client.get(reverse("user-weekly-solutions"))
        eq_(res.status_code, 200)
        # Check only 10 users information is present there
        eq_(len(res.data), 10)
        # Create a list of the data with only the ``username`` and ``weekly_solutions``
        data_list = [(data["username"], data["weekly_solutions"])
                     for data in res.data]

        # Check only top 10 contributor information is in the API
        top_ten = user_info_list[:10]
        eq_(sorted(top_ten), sorted(data_list))

    def test_email_visible_when_signed_in(self):
        p = ProfileFactory()
        url = reverse("user-detail", args=[p.user.username])
        self.client.force_authenticate(user=p.user)
        res = self.client.get(url)
        eq_(res.data["email"], p.user.email)

    def test_email_not_visible_when_signed_out(self):
        p = ProfileFactory()
        url = reverse("user-detail", args=[p.user.username])
        res = self.client.get(url)
        assert "email" not in res.data

    def test_settings_visible_when_signed_in(self):
        p = ProfileFactory()
        p.settings.create(name="foo", value="bar")
        url = reverse("user-detail", args=[p.user.username])
        self.client.force_authenticate(user=p.user)
        res = self.client.get(url)
        eq_(res.data["settings"], [{"name": "foo", "value": "bar"}])

    def test_settings_not_visible_when_signed_out(self):
        p = ProfileFactory()
        p.settings.create(name="foo", value="bar")
        url = reverse("user-detail", args=[p.user.username])
        res = self.client.get(url)
        assert "settings" not in res.data

    def test_is_active(self):
        p = ProfileFactory()
        url = reverse("user-detail", args=[p.user.username])
        res = self.client.get(url)
        assert "is_active" in res.data

    def test_avatar_size(self):
        p = ProfileFactory()
        url = reverse("user-detail", args=[p.user.username])

        res = self.client.get(url)
        assert "?s=200" in res.data["avatar"]

        res = self.client.get(url, {"avatar_size": 128})
        assert "?s=128" in res.data["avatar"]
class MeasurementsEndPointsTestCase(TestCase):
    def setUp(self):
        self.__user = CustomUser.objects.create(username="******",
                                                email="*****@*****.**",
                                                name="Admin's name",
                                                user_type="adm",
                                                password="******")
        self.__user.save()
        self.__credentials = ("admin", "admin")
        self.__api_client = APIClient()
        self.__minutely_apparent_three_phase = "/graph/minutely_apparent_power/"

    def test_get_with_auth_minutely_apparent_power_three_phase(self):
        self.__api_client.login(username="******", password="******")
        response = self.__api_client.get(
            self.__minutely_apparent_three_phase)
        self.__api_client.logout()
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_without_auth_minutely_apparent_power_three_phase(self):
        response = self.__api_client.get(
            self.__minutely_apparent_three_phase)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_post_with_auth_minutely_apparent_power_three_phase(self):
        self.__api_client.login(username="******", password="******")
        response = self.__api_client.post(
            self.__minutely_apparent_three_phase)
        self.__api_client.logout()
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

    def test_post_without_auth_minutely_apparent_power_three_phase(self):
        response = self.__api_client.post(
            self.__minutely_apparent_three_phase)
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

    def test_put_with_auth_minutely_apparent_power_three_phase(self):
        self.__api_client.login(username="******", password="******")
        response = self.__api_client.put(
            self.__minutely_apparent_three_phase)
        self.__api_client.logout()
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

    def test_put_without_auth_minutely_apparent_power_three_phase(self):
        response = self.__api_client.put(
            self.__minutely_apparent_three_phase)
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

    def test_delete_with_auth_minutely_apparent_power_three_phase(self):
        self.__api_client.login(username="******", password="******")
        response = self.__api_client.delete(
            self.__minutely_apparent_three_phase)
        self.__api_client.logout()
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

    def test_delete_without_auth_minutely_apparent_power_three_phase(self):
        response = self.__api_client.delete(
            self.__minutely_apparent_three_phase)
        self.assertEqual(response.status_code,
                         status.HTTP_401_UNAUTHORIZED)
class BasicTestCase(TestCase):
    def setUp(self):
        self.c = APIClient()
        self.user = User.objects.create_user(username='******', password='******')
        self.c.login(username='******', password='******')

    def test_new_reservierung_fail(self):
        response = self.c.post('/api/reservierung/',
                               {'title': 'new reservierung'})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_new_reservierung_ok(self):
        # Reservierung anlegen
        response = self.c.post('/api/reservierung/', {
            'kg': 4584,
            'kunde': 210
        })
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        BASE_URL = response.data['url']

        # add 4 Grundstücke
        res2 = self.c.post(BASE_URL + 'add_gpkt/', {
            'kg': 56543,
            'point_nums': 4
        })
        self.assertEqual(len(res2.data['punkt_set']), 4)

        # check status of Reservation - must be in 'ANGELEGT'
        res3 = self.c.get(BASE_URL)
        self.assertEqual(res3.data['status'], 'A')

        # Reservierung löschen
        res4 = self.c.delete(BASE_URL)
        self.assertEqual(res4.status_code, status.HTTP_200_OK)

    def test_new_reservierung_deletegpkt(self):
        # Reservierung anlegen
        response = self.c.post('/api/reservierung/', {
            'kg': 4584,
            'kunde': 210
        })
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        BASE_URL = response.data['url']

        res2 = self.c.post(BASE_URL + 'add_gpkt/', {
            'kg': 56543,
            'point_nums': 4
        })
        self.assertEqual(len(res2.data['punkt_set']), 4)

        res3 = self.c.put(BASE_URL + 'set_progress/', {
            'kg': 56543,
            'point_nums': 4
        })
        self.assertEqual(res3.data['status'], 'B')

        res4 = self.c.delete(BASE_URL + 'del_gpkt/', {'points': '14,35,56'})
        self.assertEqual(len(res4.data['punkt_set']), 4)

        res5 = self.c.delete(BASE_URL + 'del_gpkt/', {'points': '1,2,3'})
        self.assertEqual(len(res5.data['punkt_set']), 1)

        # Reservierung updaten
        res7 = self.c.put(BASE_URL, {'points': '5,6', 'kg': 4567})
        self.assertEqual(res7.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        res8 = self.c.patch(BASE_URL, {'points': '5,6', 'kg': 4567})
        self.assertEqual(res8.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

        # Reservierung löschen
        res6 = self.c.delete(BASE_URL)
        self.assertEqual(res6.status_code, status.HTTP_400_BAD_REQUEST)

        res9 = self.c.put(BASE_URL + 'set_done/')
        self.assertEqual(res9.status_code, status.HTTP_200_OK)
Exemple #58
0
class Course_Test(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username='******',
                                             password='******')
        self.course = Course.objects.create(subject="MATH",
                                            number=323,
                                            term='201909',
                                            description='test course')
        self.data = {'username': '******', 'password': '******'}
        self.client.post(reverse('login'), data=self.data)
        token = Token.objects.get(user=self.user)
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

    def test_course_create(self):
        url = reverse('course_create')
        data = {
            'subject': 'MATH',
            'number': 324,
            'term': '201909',
            'description': 'test course'
        }
        response = self.client.post(url, data=data)
        self.assertEqual(Course.objects.count(), 2)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        response = response.json()
        self.assertEqual(response['subject'], 'MATH')
        self.assertEqual(response['number'], 324)
        self.assertEqual(response['term'], '201909')
        self.assertEqual(response['description'], 'test course')
        self.assertEqual(response['time_chosed'], 0)
        self.assertFalse(response['isAvailable'])
        self.assertEqual(response['price'], 0)
        self.assertIsNone(response['tutor'], 0)

    def test_get_courses(self):
        self.client.credentials(HTTP_AUTHORIZATION='')
        url = reverse('course_list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = response.json()
        course_json = CourseSerializer(self.course)
        self.assertEqual(response[0], course_json.data)

    def test_course_detail(self):
        """
        Retrieve a course
        """
        url = reverse('course_detail', args=[1])
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = response.json()
        course_json = CourseSerializer(self.course)
        self.assertEqual(response, course_json.data)
        """
        Update a course
        """
        data = {"tutor": 1}
        response = self.client.patch(url, data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = response.json()
        self.course.tutor = self.user
        course_json = CourseSerializer(self.course)
        self.assertEqual(response, course_json.data)
        """
        Delete a course
        """
        self.assertEqual(Course.objects.count(), 1)
        self.client.delete(url)
        self.assertEqual(Course.objects.count(), 0)

    def test_cart_create(self):
        url = reverse('cart_list')
        data = {
            'number': 1,
            'total': 50,
            'user': self.user.id,
            'course': self.course.id
        }
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        response = response.json()
        self.assertEqual(response['number'], 1)
        self.assertEqual(response['total'], 50)
        self.assertEqual(response['user'], self.user.id)
        self.assertEqual(response['course'], self.course.id)
        self.assertEqual(ShoppingCart.objects.count(), 1)

    def test_get_carts(self):
        url = reverse('cart_list')
        data = {'user': 1, 'course': self.course.id}
        self.client.post(url, data)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response = response.json()[0]
        self.assertEqual(response['user'], self.user.id)
        self.assertEqual(response['course'], self.course.id)
        self.assertEqual(ShoppingCart.objects.count(), 1)
Exemple #59
0
class APITestCase(TestCase):

    def setUp(self):
        self.model              = MODEL
        self.serializer_class   = SERIALIZER_CLASS
        self.create_data        = CREATE_DATA
        self.expect_data        = EXPECT_DATA
        self.update_data        = UPDATE_DATA
        self.update_expect_data = UPDATE_EXPECT_DATA.copy()
        self.update_expect_data['join_date'] = '2001-01-01T00:00:00'

        self.client =  APIClient()
        self.entity = 'member'
        self.api_end_point = '/api/v1/members/'

    def test_create(self):
        response = self.client.post(self.api_end_point, self.create_data)
        self.assertEqual(response.status_code, 201, "Created new instance")

        # compare response to expected data
        for key, expected_value in self.expect_data.items():
            instance_value = response.data.get(key)
            self.assertEqual(instance_value, expected_value, "Comparing {} attribute".format(key) )

        # verify actual database record was created
        instance = self.model.objects.get(id=response.data.get('id'))
        self.assertTrue(instance)

    def test_retrieve(self):
        response = self.client.post(self.api_end_point, self.create_data)
        self.assertEqual(response.status_code, 201, "Created new instance")

        instance_id = response.data.get('id')
        uri = "{}{}/".format(self.api_end_point,instance_id)
        self.assertEqual(response.status_code, 201, "Retrieved")

        response = None
        response = self.client.get(uri)

        # compare response to expected data
        for key, expected_value in self.expect_data.items():
            instance_value = response.data.get(key)
            self.assertEqual(instance_value, expected_value, "Comparing {} attribute".format(key) )

    def test_update(self):
        response = self.client.post(self.api_end_point, self.create_data)
        self.assertEqual(response.status_code, 201, "Created new instance")

        instance_id = response.data.get('id')
        uri = "{}{}/".format(self.api_end_point,instance_id)

        response = self.client.patch(uri, json.dumps(self.update_data), content_type='application/json')
        self.assertEqual(response.status_code, 200, "Updated instance")

        # validate response
        for key, expected_value in self.update_expect_data.items():
            instance_value = response.data.get(key)
            self.assertEqual(instance_value, expected_value, "Comparing {} attribute".format(key) )

        # perform get operation and validate
        instance_id = response.data.get('id')
        uri = "{}{}/".format(self.api_end_point,instance_id)

        response = None
        response = self.client.get(uri)

        # compare response to expected data
        for key, expected_value in self.update_expect_data.items():
            instance_value = response.data.get(key)
            self.assertEqual(instance_value, expected_value, "Comparing {} attribute".format(key) )

    def test_delete(self):
        response = self.client.post(self.api_end_point, self.create_data)
        self.assertEqual(response.status_code, 201, "Created new instance")

        instance_id = response.data.get('id')
        uri = "{}{}/".format(self.api_end_point,instance_id)

        response = self.client.delete( uri )    
        self.assertEqual(response.status_code, 204, "Deleted")

        query = self.model.objects.filter(id=instance_id)
        self.assertEqual(len(query),0, "Deleted")

    def test_list(self):

        # create an organization
        organization = Organization.objects.create(name="Planet Express")

        # create people
        data = [
            {'title': 'Mr.', 'first_name':'Ben'     , 'last_name':'Grimm'   , 'birthday': '1980-01-01', 'gender':'m'},
            {'title': 'Mr.', 'first_name':'Johnny'  , 'last_name':'Storm'   , 'birthday': '1990-07-11', 'gender':'m'},
            {'title': 'Miss', 'first_name':'Sue'    , 'last_name':'Storm'   , 'birthday': '1989-12-28', 'gender':'f'},
            {'title': 'Dr.', 'first_name':'Reed'    , 'last_name':'Richards', 'birthday': '1969-04-11', 'gender':'m'}
        ]
        for idata in data:
            person = Person.objects.create(**idata )
            member = Member.objects.create(progenitor=organization.moniker(),person=person,join_date='2001-01-01')
        
        # list results
        response = None
        response = self.client.get(self.api_end_point)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 4)

        # filter - progenitor
        response = None
        response = self.client.get(self.api_end_point+'?progenitor=organization:1')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 4)

        # filter - join date exact
        response = None
        response = self.client.get(self.api_end_point+'?join_date=2001-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 4)

        # filter - join date gt
        response = None
        response = self.client.get(self.api_end_point+'?join_date__gt=2001-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 0)        

        response = None
        response = self.client.get(self.api_end_point+'?join_date__gt=2000-12-31')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 4) 

        # filter - join date lt
        response = None
        response = self.client.get(self.api_end_point+'?join_date__lt=2001-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 0)        

        response = None
        response = self.client.get(self.api_end_point+'?join_date__lt=2000-01-02')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 4)   

        # filter - birthday exact
        response = None
        response = self.client.get(self.api_end_point+'?person__birthday=1980-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)

        # filter - birthday_gt
        response = None
        response = self.client.get(self.api_end_point+'?person__birthday__gt=1985-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 2)        

        response = None
        response = self.client.get(self.api_end_point+'?person__birthday__gt=2000-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 0) 

        # filter - birthday_lt
        response = None
        response = self.client.get(self.api_end_point+'?person__birthday__lt=1985-01-01')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 2)        

        response = None
        response = self.client.get(self.api_end_point+'?person__birthday__lt=1969-04-11')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 0)    

        # filter - title
        response = None
        response = self.client.get(self.api_end_point+'?person__title=Mr.')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 2)   

        response = None
        response = self.client.get(self.api_end_point+'?person__title=Dr.')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)

        response = None
        response = self.client.get(self.api_end_point+'?person__title=Miss')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)                     

        # filter - gender
        response = None
        response = self.client.get(self.api_end_point+'?person__gender=m')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 3)   

        response = None
        response = self.client.get(self.api_end_point+'?person__gender=f')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)

        # filter - first_name
        response = None
        response = self.client.get(self.api_end_point+'?person__first_name=Ben')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1) 

        response = None
        response = self.client.get(self.api_end_point+'?person__first_name=ben')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1) 

        # filter - last_name
        response = None
        response = self.client.get(self.api_end_point+'?person__last_name=Grimm')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1) 

        response = None
        response = self.client.get(self.api_end_point+'?person__last_name=Storm')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 2) 

        response = None
        response = self.client.get(self.api_end_point+'?person__last_name=storm')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 2)      
Exemple #60
0
class TasksTests(APITestCase):
    # Create user and save token
    def setUp(self):
        self.factory = APIRequestFactory()
        self.client = APIClient()
        self.user = User.objects.create_user('testuser',
                                             email='',
                                             password='******')
        self.user.save()
        token = Token.objects.create(user=self.user)
        token.save()

    # Login user
    def _require_login(self):
        self.client.login(username='******', password='******')

    # Test get tasks by user
    def test_get_tasks(self):
        self._require_login()
        url = reverse('get_tasks')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    # Test add task
    def test_add_task(self):
        self._require_login()
        url = reverse('add_task')
        data = {'title': 'Task a', 'description': 'Description Task a'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Task.objects.get().title, 'Task a')
        return Task.objects.get(title='Task a').id

    # Test update task
    def test_update_task(self):
        test_task = self.test_add_task()
        self._require_login()
        url = reverse('update_task', kwargs={'task_id': test_task})
        data = {'title': 'Task a Updated'}
        response = self.client.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(Task.objects.get().title, 'Task a Updated')

    # Test delete task
    def test_delete_task(self):
        test_task = self.test_add_task()
        self._require_login()
        url = reverse('delete_task', kwargs={'task_id': test_task})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    # Test search task by description
    def test_search_task(self):
        self.test_add_task()
        self._require_login()
        url = reverse('search_task')
        data = {'description': 'Task'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    # Test change status task
    def test_change_status(self):
        test_task = self.test_add_task()
        self._require_login()
        url = reverse('change_state', kwargs={'task_id': test_task})
        data = {'status': True}
        response = self.client.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(Task.objects.get(id=test_task).status, True)