def test_anonymous_request(self):
     client = APIClient()
     response = client.get('/', HTTP_ACCEPT='application/vnd.coreapi+json')
     self.assertEqual(response.status_code, 200)
     expected = coreapi.Document(
         url='',
         title='Example API',
         content={
             'example': {
                 'list': coreapi.Link(
                     url='/example/',
                     action='get',
                     fields=[
                         coreapi.Field('page', required=False, location='query'),
                         coreapi.Field('ordering', required=False, location='query')
                     ]
                 ),
                 'retrieve': coreapi.Link(
                     url='/example/{pk}/',
                     action='get',
                     fields=[
                         coreapi.Field('pk', required=True, location='path')
                     ]
                 )
             }
         }
     )
     self.assertEqual(response.data, expected)
Пример #2
0
class UserTests(APITestCase):

    def test_create_user(self):
        self.client = APIClient()
        data = {'first_name': '123', 'last_name': '123', 'email': '*****@*****.**',
                'password': '******', 'phone': '123'}
        self.client.post('/api/user/', data, format='json')
Пример #3
0
class TestUserLoginView(TestCase):
    url = '/users/login/'

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

    def test_get(self):
        response = self.client.get(self.url)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            json.loads(response.content.decode()).get('info_text'))

    def test_post_no_data(self):
        response = self.client.post(self.url)

        self.assertEqual(response.status_code, 400)

    def test_post_correct_data(self):
        response = self.client.post(
            self.url,
            {'username': '******', 'password': '******'})

        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content.decode()).get('user_id'), 1)

    def test_post_incorrect_data(self):
        response = self.client.post(
            self.url,
            {'username': '******', 'password': '******'})

        self.assertEqual(response.status_code, 400)
Пример #4
0
    def test_make_build(self):
        """
        Test that a superuser can use the API
        """
        client = APIClient()
        client.login(username='******', password='******')
        resp = client.post(
            '/api/v2/build/',
            {
                'project': 1,
                'version': 1,
                'success': True,
                'output': 'Test Output',
                'error': 'Test Error',
                'state': 'cloning',
            },
            format='json')
        self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
        build = resp.data
        self.assertEqual(build['state_display'], 'Cloning')

        resp = client.get('/api/v2/build/%s/' % build['id'])
        self.assertEqual(resp.status_code, 200)
        build = resp.data
        self.assertEqual(build['output'], 'Test Output')
        self.assertEqual(build['state_display'], 'Cloning')
Пример #5
0
def get_authorized_client(user):
    token = Token.objects.create(user=user)

    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

    return client
Пример #6
0
    def test_list(self, user1):
        client = APIClient()
        client.force_authenticate(user=user1)

        response = client.get(reverse('node-list'))

        assert response.status_code == status.HTTP_200_OK
Пример #7
0
    def test_perm(self):
        client = APIClient()

        response = client.get(reverse('node-list'))

        # user not logged
        assert response.status_code == status.HTTP_403_FORBIDDEN
Пример #8
0
 def test_login_not_doctor_nor_patient_fails(self):
     """
     Login of an existing user not associated with doctor nor patient causes 401
     """
     client = APIClient()
     response = client.post('/nocc/api/v1/auth/login/', {'username': '******', 'password': '******'}, format='json')
     self.assertEqual(response.status_code, 401)
Пример #9
0
def api_client(user, db):
    """
    A rest_framework api test client not auth'd.
    """
    client = APIClient()
    client.force_authenticate(user=user)
    return client
Пример #10
0
 def test_anonymous(self):
     """Verifies that an anonymous client cannot access the team
     dashboard, and is redirected to the login page."""
     anonymous_client = APIClient()
     response = anonymous_client.get(self.teams_url)
     redirect_url = '{0}?next={1}'.format(settings.LOGIN_URL, self.teams_url)
     self.assertRedirects(response, redirect_url)
Пример #11
0
 def login_client(self, user):
     """
     Helper method for getting the client and user and logging in. Returns client.
     """
     client = APIClient()
     client.login(username=user.username, password=self.TEST_PASSWORD)
     return client
Пример #12
0
def create_client(user, url, get=True, kwargs=None):
    token = Token.objects.get_or_create(user=user)[0]
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
    if get:
        return client.get(url, kwargs=kwargs)
    return client.post(url, data=kwargs)
Пример #13
0
    def test_queueing(self, mocked_now):
        test_datetime = datetime.utcnow().isoformat() + 'Z'

        mocked_now.return_value = test_datetime

        task_post_data = {
            'task_def': self.task_def_name,
            'data': {
                'foo': 'bar'
            }
        }

        client = APIClient()
        client.credentials(HTTP_AUTHORIZATION=self.token)

        response = client.post('/tasks', task_post_data, format='json')

        self.assertEqual(response.status_code, 201)
        self.assertEqual(list(response.data.keys()), task_keys)
        self.assertEqual(response.data['task_def'], self.task_def_name)

        ## test fields defaults
        self.assertEqual(response.data['status'], 'queued')
        self.assertEqual(response.data['priority'], 'normal')
        self.assertEqual(response.data['run_at'], test_datetime)
Пример #14
0
class UserViewSetTestCase(APITestCase, TestCaseUtils):
    def setUp(self):
        self.client = APIClient()
        self.factory = APIRequestFactory()
        self.dev_user = User.objects.create_user("dev_user", "*****@*****.**", "123456")
        self.post_view = UserViewSet.as_view({"post": "create"})

        self.application = Application(
            name="Test Password Application",
            user=self.dev_user,
            client_type=Application.CLIENT_PUBLIC,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )
        self.application.save()

    def test_signup_new_user(self):
        new_user = {"grant_type": "password", "username": "******", "password": "******"}
        auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
        response = self.client.post(reverse("user-list"), data=new_user, **auth_headers)
        self.assertEqual(User.objects.count(), 2)

    def test_signup_bad_request(self):
        new_user = {"grant_type": "password", "username": "******"}
        auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
        response = self.client.post(reverse("user-list"), data=new_user, **auth_headers)
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def tearDown(self):
        self.application.delete()
        self.dev_user.delete()
Пример #15
0
    def test_get_product_with_auth(self):

        c = APIClient()
        c.login(username='******', password='******')
        response = c.get('/products/1/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.content, '{"id":1,"owner":"bruce","name":"Bat Mobile","description":"Black Batmobile","price":200,"category":"Automobile","image":""}')
Пример #16
0
class TestCharmessageDBQueries(TestCase):
    """
    Tests that receiving elements only need the required db queries.

    Therefore in setup some objects are created and received with different
    user accounts.
    """

    def setUp(self):
        self.client = APIClient()
        config['general_system_enable_anonymous'] = True
        user = User.objects.get(pk=1)
        for index in range(10):
            ChatMessage.objects.create(user=user)

    @use_cache()
    def test_admin(self):
        """
        Tests that only the following db queries are done:
        * 4 requests to get the session an the request user with its permissions,
        * 2 requests to get the list of all chatmessages,
        """
        self.client.force_login(User.objects.get(pk=1))
        with self.assertNumQueries(6):
            self.client.get(reverse('chatmessage-list'))
Пример #17
0
class TestAccountAPITransactions(TransactionTestCase):
    """
    Tests the transactional behavior of the account API
    """
    test_password = "******"

    def setUp(self):
        super(TestAccountAPITransactions, self).setUp()
        self.client = APIClient()
        self.user = UserFactory.create(password=self.test_password)
        self.url = reverse("accounts_api", kwargs={'username': self.user.username})

    @patch('student.views.do_email_change_request')
    def test_update_account_settings_rollback(self, mock_email_change):
        """
        Verify that updating account settings is transactional when a failure happens.
        """
        # Send a PATCH request with updates to both profile information and email.
        # Throw an error from the method that is used to process the email change request
        # (this is the last thing done in the api method). Verify that the profile did not change.
        mock_email_change.side_effect = [ValueError, "mock value error thrown"]
        self.client.login(username=self.user.username, password=self.test_password)
        old_email = self.user.email

        json_data = {"email": "*****@*****.**", "gender": "o"}
        response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json")
        self.assertEqual(400, response.status_code)

        # Verify that GET returns the original preferences
        response = self.client.get(self.url)
        data = response.data
        self.assertEqual(old_email, data["email"])
        self.assertEqual(u"m", data["gender"])
def test_create_bug_job_map(eleven_jobs_processed, mock_message_broker, jm):
    """
    test creating a single note via endpoint
    """

    client = APIClient()
    user = User.objects.create(username="******", is_staff=True)
    client.force_authenticate(user=user)

    job = jm.get_job_list(0, 1)[0]

    bug_job_map_obj = {
        "job_id": job["id"],
        "bug_id": 1,
        "type": "manual"
    }

    client.post(
        reverse("bug-job-map-list", kwargs={"project": jm.project}),
        bug_job_map_obj
    )

    user.delete()

    assert (bug_job_map_obj,) == jm.get_bug_job_map_list(0, 1)

    jm.disconnect()
Пример #19
0
 def test_jwt_login_custom_response_json(self):
     """
     Ensure JWT login view using JSON POST works.
     """
     client = APIClient(enforce_csrf_checks=True)
     response = client.post('/auth-token/',format='json')
     self.assertTrue(response.status_code, status.HTTP_200_OK)
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()
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()
Пример #22
0
class GroupTests(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.cl =  Client.objects.create(user=self.user,
                                         redirect_uri="http://localhost/",
                                         client_type=2
        )

        self.token = AccessToken.objects.create(
            user=self.user, client=self.cl,
            expires=datetime.date(
                year=2015, month=1, day=2
            )
        )
        self.client = APIClient()

        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.token)


    def test_create_group(self):
        """
        Ensure we can create a group.
        """
        url = reverse('group-create')
        data = { 'name': 'SECSI',
                'description': 'SECSI, DO YOU SPEAK IT', 'creator': self.user.id}
        response = self.client.post(url + ".json", data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
 def setUp(self):
     self.csrf_client = APIClient(enforce_csrf_checks=True)
     self.non_csrf_client = APIClient(enforce_csrf_checks=False)
     self.username = '******'
     self.email = '*****@*****.**'
     self.password = '******'
     self.user = User.objects.create_user(self.username, self.email, self.password)
Пример #24
0
class UserAPITest(APITestCase):

    fixtures = ['user.json']

    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.get(email='*****@*****.**')
        payload = jwt_payload_handler(self.user)
        self.token = utils.jwt_encode_handler(payload)


    def testUpdateAccountDetails(self):
        auth = 'JWT {0}'.format(self.token)

        response = self.client.patch('/api/account/{}'.format(self.user.id),
            {
                "contact_number": '09175226502'
            }, HTTP_AUTHORIZATION=auth, format='json')

    def testChangePassword(self):
        auth = 'JWT {0}'.format(self.token)
        user = User.objects.get(email='*****@*****.**')

        response = self.client.patch('/api/change_password'.format(self.user.id),
            {
                "password": '******',
                "old_password": '******'
            }, HTTP_AUTHORIZATION=auth, format='json')

        print(user.password)
        user = User.objects.get(email='*****@*****.**')
        print(user.password)
Пример #25
0
class XeroxViewTest(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.sizes = ('q', 'n')
        self.urls = {}
        self.nurls = {}
        x_hash = XeroxMachine().add('http://www.google.com/google.jpg')
        no_hash = XeroxMachine().add('http://zarautz.xyz/open.jpg')
        for size in self.sizes:
            self.urls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, x_hash, size)))
            self.nurls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, no_hash, size)))

    def test_default_response(self):
        response = self.client.get(self.urls[self.sizes[0]])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response['Content-Type'], 'image/jpeg')
        self.assertEqual(response['Cache-Control'], 'max-age=604800')

    def test_no_response(self):
        response = self.client.get(self.nurls[self.sizes[0]])
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_no_event_response(self):
        response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/e/'))  # EventImage
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_no_place_response(self):
        response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/p/'))  # PlaceImage
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_image_sizes(self):
        for size in self.sizes:
            image = Image.open(StringIO(self.client.get(self.urls[size]).content))
            self.assertEqual(image.size[0], IMAGE_SIZES[size]['size'][0])
Пример #26
0
 def test_render_taala_detail(self):
     client = APIClient()
     client.force_authenticate(user=self.normaluser)
     response = client.get("/api/carnatic/taala/d5285bf4-c3c5-454e-a659-fec30075990b")
     data = response.data
     fields = ['aliases', 'artists', 'common_name', 'composers', 'name', 'recordings', 'uuid', 'works']
     self.assertEqual(fields, sorted(data.keys()))
Пример #27
0
    def test_get(self):
        client = APIClient()
        response = client.get('/sources')

        response.status_code.should.eql(status.HTTP_200_OK)

        response.data.should.eql(['youtube', 'soundcloud'])
 def test_token_login_form(self):
     """Ensure token login view using form POST works."""
     client = APIClient(enforce_csrf_checks=True)
     response = client.post('/auth-token/',
                            {'username': self.username, 'password': self.password})
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data['token'], self.key)
Пример #29
0
def test_update_failure_line_replace(eleven_jobs_stored, jm, failure_lines,
                                     classified_failures, test_user):

    MatcherManager.register_detector(ManualDetector)

    client = APIClient()
    client.force_authenticate(user=test_user)

    failure_line = failure_lines[0]
    assert failure_line.best_classification == classified_failures[0]
    assert failure_line.best_is_verified is False

    body = {"project": jm.project,
            "best_classification": classified_failures[1].id}

    resp = client.put(
        reverse("failure-line-detail", kwargs={"pk": failure_line.id}),
        body, format="json")

    assert resp.status_code == 200

    failure_line.refresh_from_db()

    assert failure_line.best_classification == classified_failures[1]
    assert failure_line.best_is_verified
    assert len(failure_line.classified_failures.all()) == 2

    expected_matcher = Matcher.objects.get(name="ManualDetector")
    assert failure_line.matches.get(classified_failure_id=classified_failures[1].id).matcher == expected_matcher
Пример #30
0
class BaseDiscussionAclTests(TestCase):
    def setUp(self):
        self.category = CategoryFactory()
        self.user1 = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category
        )
        self.user2 = UserFactory(
            email='*****@*****.**',
            password='******',
            category=self.category
        )
        self.user3 = UserFactory(email='*****@*****.**', password='******')
        self.doc = DocumentFactory(
            category=self.category,
            revision={
                'leader': self.user1,
            }
        )
        self.client = APIClient()
        self.client.login(email=self.user1.email, password='******')
        self.doc.latest_revision.start_review()
        self.discussion_list_url = reverse('note-list', args=[self.doc.document_key, 1])
Пример #31
0
	def test_authorization_is_working(self):
		new_client = APIClient()
		res = new_client.get(reverse("items", kwargs={"version": "v1"}))
		self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
Пример #32
0
 def setUp(self):
     self.client = APIClient()
Пример #33
0
 def setUp(self):
     """Set up the customer view tests."""
     super().setUp()
     self.client = APIClient()
     self.factory = RequestFactory()
Пример #34
0
 def setUp(self):
     self.user = create_user(email='*****@*****.**', password='******', name='Anjdf')
     self.client = APIClient()
     self.client.force_authenticate(user=self.user)
Пример #35
0
class PublicUserApiTests(TestCase):
    """Test the api accessible to the public"""

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


    def test_create_user_from_endpoint(self):
        """Test that user is create successfully"""

        payload = {
            'email': '*****@*****.**',
            'password': '******',
            'name': 'Abhi'


        }

        res = self.client.post(CREATE_USER_URL, payload)

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

        user = get_user_model().objects.get(**res.data)

        self.assertTrue(user.check_password(payload['password']))
        self.assertNotIn('password', res.data)

    def test_user_exists(self):
        """Test creating a duplicate User fails"""
        payload = {'email': '*****@*****.**', 'password': '******'}

        create_user(**payload)

        res = self.client.post(CREATE_USER_URL, payload)

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

    def test_password_too_short(self):
        """Test if password is too short"""
        payload = {'email': '*****@*****.**', 'password': '******'}

        res = self.client.post(CREATE_USER_URL, payload)

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

    def test_create_token_for_user(self):
        payload = {'email': '*****@*****.**', 'password': '******'}

        create_user(**payload)

        res = self.client.post(TOKEN_URL, payload)

        self.assertIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_create_token_invalid_credentials(self):
        """Test token is not created if cred. is not real"""
        create_user(email="*****@*****.**", password='******')
        payload = {'email':"*****@*****.**", 'password':'******'}
        res = self.client.post(TOKEN_URL, payload)

        self.assertNotIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_token_no_user(self):
        """If no user, no token"""
        payload = {'email':"*****@*****.**", 'password':'******'}
        res = self.client.post(TOKEN_URL, payload)

        self.assertNotIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Пример #36
0
 def setUp(self):
     self.user = get_user_model().objects.create_user(
         '*****@*****.**', 'password123')
     self.client = APIClient()
     self.client.force_authenticate(self.user)
Пример #37
0
class PrivateApiTest(TestCase):
    """Test the authorized user tags API"""
    def setUp(self):
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'password123')
        self.client = APIClient()
        self.client.force_authenticate(self.user)

    def test_retrieve_tags(self):
        """Test retrieving tags"""
        Tag.objects.create(user=self.user, name='Vegan')
        Tag.objects.create(user=self.user, name="Dessert")

        res = self.client.get(TAGS_URL)

        tags = Tag.objects.all().order_by('-name')
        serializer = serializers.TagSerializer(tags, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_tags_limited_to_user(self):
        """Test that tags returned are for the authenticated user"""

        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'password123test')

        Tag.objects.create(user=user2, name='Fruity')
        tag = Tag.objects.create(user=self.user, name='Comfort_food')

        res = self.client.get(TAGS_URL)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        self.assertEqual(res.data[0]['name'], tag.name)

    def test_create_tag_successful(self):
        """Test creating a new tag"""

        payload = {'name': 'test tag'}
        self.client.post(TAGS_URL, payload)

        exists = Tag.objects.filter(user=self.user,
                                    name=payload['name']).exists()
        self.assertTrue(exists)

    def test_create_tag_invalid(self):
        """Test creating a new tag with invalid payload"""
        payload = {'name': ''}
        res = self.client.post(TAGS_URL, payload)

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

    def test_retrieve_tags_assigned_to_recipes(self):
        """Test filtering tags by those assigned to recipes"""
        tag1 = Tag.objects.create(user=self.user, name='Breakfast')
        tag2 = Tag.objects.create(user=self.user, name='Lunch')
        recipe = Recipe.objects.create(
            title='Coriander eggs on toast',
            time_minutes=10,
            price=5.00,
            user=self.user,
        )
        recipe.tags.add(tag1)

        res = self.client.get(TAGS_URL, {'assigned_only': 1})

        serializer1 = serializers.TagSerializer(tag1)
        serializer2 = serializers.TagSerializer(tag2)
        self.assertIn(serializer1.data, res.data)
        self.assertNotIn(serializer2.data, res.data)

    def test_retrieve_tags_assigned_unique(self):
        """Test filtering tags by assigned returns unique items"""
        tag = Tag.objects.create(user=self.user, name='Breakfast')
        recipe1 = Recipe.objects.create(title='Pancakes',
                                        time_minutes=5,
                                        price=3.00,
                                        user=self.user)
        recipe1.tags.add(tag)
        recipe2 = Recipe.objects.create(title='Porridge',
                                        time_minutes=3,
                                        price=2.00,
                                        user=self.user)
        recipe2.tags.add(tag)

        res = self.client.get(TAGS_URL, {'assigned_only': 1})

        self.assertEqual(len(res.data), 1)
Пример #38
0
class ContributorTestCase(APITestCase):
    '''Test cases for contributor and maintainer views.'''
    def setUp(self):
        '''Initial setup'''
        self.client = APIClient()
        self.contributor = self.client.post('/api/auth/registration/',
                                            data={
                                                'first_name': 'contry',
                                                'last_name': 'user',
                                                'password1': 'passworddd1234',
                                                'password2': 'passworddd1234',
                                                'email': '*****@*****.**',
                                                'username': '******',
                                                'town_city': 'Ikeja',
                                                'state': 'Lagos',
                                                'country': 'NG'
                                            })

        self.contributor2 = self.client.post('/api/auth/registration/',
                                             data={
                                                 'first_name': 'contry',
                                                 'last_name': 'user',
                                                 'password1': 'passworddd1234',
                                                 'password2': 'passworddd1234',
                                                 'email': '*****@*****.**',
                                                 'username': '******',
                                                 'town_city': 'Ikeja',
                                                 'state': 'Lagos',
                                                 'country': 'NG'
                                             })

        self.maintainer = self.client.post('/api/auth/registration/',
                                           data={
                                               'first_name': 'test',
                                               'last_name': 'user',
                                               'password1': 'passworddd1234',
                                               'password2': 'passworddd1234',
                                               'email': '*****@*****.**',
                                               'username': '******',
                                               'town_city': 'Ikeja',
                                               'state': 'Lagos',
                                               'country': 'NG'
                                           })
        # get contributors.
        self.user = get_user_model().objects.get(email='*****@*****.**')
        self.contrib2 = get_user_model().objects.get(
            email='*****@*****.**')

        self.response = self.client.post(reverse('rest_login'),
                                         data={
                                             'email': '*****@*****.**',
                                             'password': '******',
                                         })

        self.token = self.response.data['access_token']

        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token)

    def test_contributor_can_be_blacklisted(self):
        '''Test contributor can blacklisted successfully by a maintainer.'''
        # make user a maintainer.
        maintainer = get_user_model().objects.get(email='*****@*****.**')
        maintainer.is_contributor = False
        maintainer.is_maintainer = True
        maintainer.save()

        data = {
            'contributor': self.user.id,
            'maintainer': maintainer.id,
            'reason': 'Fake account. Uploaded misleading info 3 times.',
        }
        response = self.client.post('/api/blacklist/', data=data)

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

    def test_contributor_fails_to_be_blacklisted(self):
        '''
        Test contributor cannot blacklisted if `user` type trying to 
        blacklist is NOT maintainer or admin.
        '''
        # does not assign a `user` type.
        not_maintainer = get_user_model().objects.get(email='*****@*****.**')

        data = {
            'contributor': self.user.id,
            'maintainer': not_maintainer.id,
            'reason': 'Fake account. Uploaded misleading info 3 times.'
        }

        response = self.client.post('/api/blacklist/', data=data)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_maintainer_can_remove_contributor_from_blacklist(self):
        '''Test maintainer can delete a blacklist entry.'''
        maintainer = get_user_model().objects.get(email='*****@*****.**')
        maintainer.is_contributor = False
        maintainer.is_maintainer = True
        maintainer.save()

        data = {
            'contributor': self.contrib2.id,
            'maintainer': maintainer.id,
            'reason': 'Fake account. Uploaded misleading info 3 times.',
        }
        added_blacklist = self.client.post('/api/blacklist/', data=data)

        url = '/api/blacklist/' + str(added_blacklist.data['id']) + '/'

        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    def test_falis_remove_contributor_from_blacklist(self):
        '''Test non-maintainer or admin type cannot delete a blacklist entry.'''
        maintainer = get_user_model().objects.get(email='*****@*****.**')
        maintainer.is_contributor = False
        maintainer.is_maintainer = True
        maintainer.save()

        data = {
            'contributor': self.contrib2.id,
            'maintainer': maintainer.id,
            'reason': 'Fake account again.',
        }
        added_blacklist = self.client.post('/api/blacklist/', data=data)

        not_maintainer = get_user_model().objects.get(email='*****@*****.**')
        not_maintainer.is_maintainer = False
        not_maintainer.save()

        url = '/api/blacklist/' + str(added_blacklist.data['id']) + '/'

        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Пример #39
0
def client():
    return APIClient()
Пример #40
0
class UserTestCase(APITestCase):
    '''Test cases for user authentication views.'''
    def setUp(self):
        '''Initial setup'''
        self.client = APIClient()
        self.user = self.client.post('/api/auth/registration/',
                                     data={
                                         'first_name': 'test',
                                         'last_name': 'user',
                                         'password1': 'passworddd1234',
                                         'password2': 'passworddd1234',
                                         'email': '*****@*****.**',
                                         'username': '******',
                                         'town_city': 'Ikeja',
                                         'state': 'Lagos',
                                         'country': 'NG'
                                     })

        self.response = self.client.post(reverse('rest_login'),
                                         data={
                                             'email': '*****@*****.**',
                                             'password': '******',
                                         })
        self.token = self.response.data['access_token']

        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token)

    def test_user_login(self):
        '''Test user can login after registration.'''
        response = self.client.post(reverse('rest_login'),
                                    data={
                                        'email': '*****@*****.**',
                                        'password': '******',
                                    })

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

    def test_user_cannot_login_with_wrong_credentials(self):
        '''Test fails with incorrect login credentials.'''
        response = self.client.post(reverse('rest_login'),
                                    data={
                                        'email': '*****@*****.**',
                                        'password': '******',
                                    })

        self.assertNotEqual(response.status_code, status.HTTP_200_OK)

    def test_user_profile_retrieval(self):
        '''Test user can retrieve their details from url.'''
        data = {'email': '*****@*****.**'}
        response = self.client.get('/api/auth/user/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_user_profile_update(self):
        """Test user can make updates to their profile"""
        updated_data = {"username": "******"}
        response = self.client.patch('/api/auth/user/',
                                     data=updated_data,
                                     format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['username'], "Just-Me")
Пример #41
0
class ViewTestCase(TestCase):
    """Test suite for the api views."""
    def setUp(self):
        """Define the test client and other test variables."""
        self.client = APIClient()
        self.user = User.objects.create_user(username='******', password='******')
        self.entry_data = {'text': 'Write code for BuJo API'}
        self.response = ''

    def login(self):
        """ Log in with valid credentials """
        self.client.login(username='******', password='******')

    def logout(self):
        """ Log out """
        self.client.logout()

    def post(self):
        """ Post data to the create entry endpoint """
        self.response = self.client.post(reverse('entry-list'),
                                         self.entry_data,
                                         format="json")

    def create_authenticated_entry(self):
        """ Create an entry after authentication """
        self.login()
        self.post()
        self.logout()

    def update_entry(self, entry_id):
        """ Update the entry with entry_id """
        change_entry = {'text': 'Changed Entry'}
        response = self.client.put(reverse('entry-detail',
                                           kwargs={'pk': entry_id}),
                                   change_entry,
                                   format='json')
        return response

    def test_api_can_create_an_entry(self):
        """Test the api has entry creation capability."""
        self.create_authenticated_entry()
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    def test_api_can_get_all_entries(self):
        """Test the api can get all entries."""
        self.create_authenticated_entry()
        self.create_authenticated_entry()

        self.login()
        response = self.client.get(reverse('entry-list'), format="json")
        self.logout()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 2)

    def test_api_can_get_an_entry(self):
        """Test the api can get a given entry."""
        self.create_authenticated_entry()
        entry = Entry.objects.get()
        self.login()
        response = self.client.get(reverse('entry-detail',
                                           kwargs={'pk': entry.id}),
                                   format="json")
        self.logout()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, entry)

    def test_api_can_update_entry(self):
        """Test the api can update a given entry."""
        self.create_authenticated_entry()
        entry = Entry.objects.get()

        self.login()
        response = self.update_entry(entry.id)
        self.logout()

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

    def test_api_can_delete_entry(self):
        """Test the api can delete an entry."""
        self.create_authenticated_entry()
        entry = Entry.objects.get()

        self.login()
        response = self.client.delete(reverse('entry-detail',
                                              kwargs={'pk': entry.id}),
                                      format='json',
                                      follow=True)
        self.logout()

        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEquals(Entry.objects.count(), 0)

    def test_unauth_api_not_crud_entry(self):
        """ Test the api won't allow unauthenticated users to post/get/put/delete """
        # create
        self.post()
        self.assertEqual(self.response.status_code,
                         status.HTTP_401_UNAUTHORIZED)

        self.create_authenticated_entry()
        entry = Entry.objects.get()
        self.create_authenticated_entry()

        # read
        response = self.client.get(reverse('entry-list'), format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        response = self.client.get(reverse('entry-detail',
                                           kwargs={'pk': entry.id}),
                                   format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # update
        response = self.update_entry(entry.id)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # delete
        response = self.client.delete(reverse('entry-detail',
                                              kwargs={'pk': entry.id}),
                                      format='json',
                                      follow=True)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
class TestCrfQuestion(TestCase):
    def setUp(self):
        admin = CurationUser.objects.get(email='*****@*****.**')
        self.client = APIClient()
        self.client.force_authenticate(user=admin)
        self.crf_question1=CRFQuestion.objects.create(text ='some text',
            description ='some description',
            type = 'some type',
            responses ='responses',
            note='our note')
        self.crf_question2=CRFQuestion.objects.create(text ='some text2',
            description ='some description',
            type = 'some type',
            responses ='responses',
            note='our note')
        self.crf_question3=CRFQuestion.objects.create(text ='some text3',
            description ='some description',
            type = 'some type',
            responses ='responses',
            note='our note')

        self.valid_crfquestion_input={
            'text': 'some text4',
            'description' :'some description',
            'type' : 'some type',
            'responses' :'responses',
            'note':'our note'
        }

        self.invalid_crfquestion_input={
            'text': 'some text5',
            'description' :'some description',
            'type' : '',
            'responses' :'responses',
            'note':'our note'
        }
        self.valid_crfquestion_update={
            'text': 'some text6',
            'description' :'some description',
            'type' : 'some type',
            'responses' :'responses',
            'note':'our note'
        }

    def test_get_crf_questions(self):
        url = '/clinical/crfquestions/'
        response = self.client.get(url)
        crf_questions = CRFQuestion.objects.all()
        serializer =CRFQuestionSerializer(crf_questions, many=True)
        #self.assertEqual(response.data, serializer.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_crf_questions_with_id(self):
        url = '/clinical/crfquestions/{id}/'.format(
            id=self.crf_question1.id
        )
        response=self.client.get(url)
        crf_question=CRFQuestion.objects.get(text='some text')
        serializer =CRFQuestionSerializer(crf_question)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    # def test_get_invalid_crf_question(self):
    #     url = '/clinical/crfquestions/{id}/'.format(
    #         id=self.crf_question1.id
    #     )
    #     response=self.client.get(url)
    #     crf_question=CRFQuestion.objects.get(text='123t')
    #     serializer =CRFQuestionSerializer(crf_question)

    def test_post_a_crf_question(self):
        url = '/clinical/crfquestions/'
        response=self.client.post(url,data=self.valid_crfquestion_input,format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_post_an_invalid_crf_question(self):
        url = '/clinical/crfquestions/'
        response=self.client.post(url,data=self.invalid_crfquestion_input,format='json')
        self.assertEqual(response.status_code,status.HTTP_400_BAD_REQUEST)

    def test_update_a_crf_question(self):
        url = '/clinical/crfquestions/{id}/'.format(
            id=self.crf_question1.id
        )
        response=self.client.put(url,data=self.valid_crfquestion_update,format='json')
        self.assertEqual(response.status_code,status.HTTP_200_OK)

    def test_update_an_invalid_crf_question(self):
        url = '/clinical/crfquestions/{id}/'.format(
            id=self.crf_question1.id
        )
        response=self.client.put(url,data=self.invalid_crfquestion_input,format='json')
        self.assertEqual(response.status_code,status.HTTP_400_BAD_REQUEST)
Пример #43
0
 def setUp(self):
     self.user = get_user_model().objects.create_user(
         '*****@*****.**', 'testpass')
     self.client = APIClient()
     self.client.force_authenticate(self.user)
Пример #44
0
 def setUp(self):
     """Define the test client and other test variables."""
     self.client = APIClient()
     self.user = User.objects.create_user(username='******', password='******')
     self.entry_data = {'text': 'Write code for BuJo API'}
     self.response = ''
Пример #45
0
 def test_authorization_is_enforced(self):
     """Test that the api has user authorization."""
     new_client = APIClient()
     response = new_client.get('/timelines/',kwargs={'pk':3},format='json')
     self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Пример #46
0
class EntryQueryTestCase(TestCase):
    """ Test suite for authentication """
    def setUp(self):
        self.client = APIClient()

        # create two users
        self.user_john = User.objects.create_user(username='******',
                                                  password='******')
        self.user_francis = User.objects.create_user(username='******',
                                                     password='******')

        self.current_time = now()
        self.yesterday = self.current_time - timedelta(days=1)
        self.two_days_ago = self.current_time - timedelta(days=2)

        # create 3 entries each with set timestamps
        entry = Entry.objects.create(text="Entry 1", user=self.user_john)
        entry.date_created = self.yesterday
        entry.save()
        entry = Entry.objects.create(text="Entry 2", user=self.user_john)
        entry.date_created = self.yesterday
        entry.save()
        entry = Entry.objects.create(text="Entry 3", user=self.user_john)

        entry = Entry.objects.create(text="Entry 1", user=self.user_francis)
        entry.date_created = self.yesterday
        entry.save()
        entry = Entry.objects.create(text="Entry 2", user=self.user_francis)
        entry = Entry.objects.create(text="Entry 3", user=self.user_francis)

    def test_api_gets_day_entries(self):
        """ Testing the get_day_entries api """
        # unauthorized request
        response = self.client.get(reverse('entry-get-day-entries'))
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # testing responses for user 1
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('entry-get-day-entries'))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 1)
        entry_names = map(lambda entry: entry['text'], response.data)
        self.assertIn('Entry 3', entry_names)

        response = self.client.get(
            reverse('entry-get-day-entries') + '?day=' + str(self.yesterday))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 2)
        entry_names = map(lambda entry: entry['text'], response.data)
        self.assertIn('Entry 1', entry_names)
        self.assertIn('Entry 2', entry_names)

        response = self.client.get(
            reverse('entry-get-day-entries') + '?day=' +
            str(self.two_days_ago))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 0)

        self.client.logout()

        # testing responses for user 2
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('entry-get-day-entries'))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 2)
        entry_names = map(lambda entry: entry['text'], response.data)
        self.assertIn('Entry 2', entry_names)
        self.assertIn('Entry 3', entry_names)

        response = self.client.get(
            reverse('entry-get-day-entries') + '?day=' + str(self.yesterday))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 1)
        entry_names = map(lambda entry: entry['text'], response.data)
        self.assertIn('Entry 1', entry_names)

        response = self.client.get(
            reverse('entry-get-day-entries') + '?day=' +
            str(self.two_days_ago))
        self.assertIsNotNone(response.data)
        self.assertEqual(len(response.data), 0)

        self.client.logout()
Пример #47
0
 def test_get_jobs_filtered_type(self):
     jobs = Job.objects.all()
     client = APIClient()
     response = client.get('/jobs/', {'type': 'prediction'})
     self.assertIsNotNone(response.data)
Пример #48
0
    def test_anon_get_answers(self):
        post = Post.objects.get(title="Join me in the next raid!")

        client = APIClient()
        response = client.get('/posts/answer/?title=' + post.title)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Пример #49
0
class RecepeImageUploadTest(TestCase):
    """ Test image uploading """

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

    def tearDown(self):
        self.recipe.image.delete()

    def test_uploading_image(self):
        """ testing valid image upload """
        url = image_uplaod_url(self.recipe.id)
        with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
            img = Image.new('RGB', (10, 10))
            img.save(ntf, format='JPEG')
            ntf.seek(0)
            res = self.client.post(url, {'image': ntf}, format='multipart')

        self.recipe.refresh_from_db()
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertIn('image', res.data)
        self.assertTrue(os.path.exists(self.recipe.image.path))

    def test_upload_image_bad(self):
        """ testing invalid image upload """
        url = image_uplaod_url(self.recipe.id)
        res = self.client.post(url, {'image': 'notimage'}, format='multipart')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_filter_recipes_by_tags(self):
        """ returning recipes by specific tags """
        recope1 = sample_recepe(user=self.user, title="Thai vegi curry")
        recope2 = sample_recepe(user=self.user, title="test thatisad")

        tag1 = sampe_tag(user=self.user, name='Vigan')
        tag2 = sampe_tag(user=self.user, name='vegitarian')
        recope1.tags.add(tag1)
        recope2.tags.add(tag2)

        recope3 = sample_recepe(user=self.user, title="Fish and chips")
        res = self.client.get(
            RECIPE_URL,
            {'tags': f'{tag1.id}, {tag2.id}'}
        )
        serialized1 = RecipeSerializer(recope1)
        serialized2 = RecipeSerializer(recope2)
        serialized3 = RecipeSerializer(recope3)
        self.assertIn(serialized1.data, res.data)
        self.assertIn(serialized2.data, res.data)
        self.assertNotIn(serialized3.data, res.data)

    def test_filter_recipes_by_ingredients(self):
        """ returning recipes by specific ingreediants """
        recope1 = sample_recepe(user=self.user, title="Thai vegi curry")
        recope2 = sample_recepe(user=self.user, title="test thatisad")

        ingredients1 = sampe_ingreedient(user=self.user, name='Test1234')
        ingredients2 = sampe_ingreedient(
            user=self.user, name='test2344521124365')
        recope1.ingreedient.add(ingredients1)
        recope2.ingreedient.add(ingredients2)

        recope3 = sample_recepe(user=self.user, title="test12e33")
        res = self.client.get(
            RECIPE_URL,
            {'ingreedient': f'{ingredients1.id}, {ingredients2.id}'}
        )
        serialized1 = RecipeSerializer(recope1)
        serialized2 = RecipeSerializer(recope2)
        serialized3 = RecipeSerializer(recope3)
        self.assertIn(serialized1.data, res.data)
        self.assertIn(serialized2.data, res.data)
        self.assertNotIn(serialized3.data, res.data)
Пример #50
0
 def test_get_jobs_filtered_status(self):
     jobs = Job.objects.all()
     client = APIClient()
     response = client.get('/jobs/', {'status': 'created'})
     self.assertIsNotNone(response.data)
Пример #51
0
class PublicUserApiTests(TestCase):
    """Test the users API (public)"""

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

    def test_create_valid_user_success(self):
        """Test creating valid user is successful"""
        payload = {
            'email': '*****@*****.**',
            'password': '******',
            'name': 'Test name'
        }
        res = self.client.post(CREATE_USER_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        user = get_user_model().objects.get(**res.data)
        self.assertTrue(user.check_password(payload['password']))
        self.assertNotIn('password', res.data)

    def test_user_exists(self):
        """Test creating user that already exist fails"""
        payload = {'email': '*****@*****.**', 'password': '******'}
        create_user(**payload)

        res = self.client.post(CREATE_USER_URL, payload)

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

    def test_password_too_short(self):
        """Test that the password must be more than 5 characters"""
        payload = {
            'email': '*****@*****.**',
            'password': '******',
        }
        res = self.client.post(CREATE_USER_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        user_exist = get_user_model().objects.filter(
            email=payload['email']
        ).exists()

        self.assertFalse(user_exist)

    def test_create_token_for_user(self):
        """Test that a token is created for the user"""
        payload = {'email':'*****@*****.**', 'password':'******'}
        create_user(**payload)
        res = self.client.post(TOKEN_URL, payload)

        self.assertIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_create_token_invalid_credentials(self):
        """Test that token is not created if invalid credentials are given"""
        create_user(email = '*****@*****.**', password = '******')
        payload = {'email':'*****@*****.**', 'password':'******'}
        res = self.client.post(TOKEN_URL, payload)

        self.assertNotIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_token_no_user(self):
        """Test that token is not created if user doesn't exist"""
        payload = {'email':'*****@*****.**', 'password':'******'}
        res = self.client.post(TOKEN_URL, payload)

        self.assertNotIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_token_missing_field(self):
        """Test that email and password are required"""
        payload = {'email':'one', 'password':''}
        res = self.client.post(TOKEN_URL, payload)

        self.assertNotIn('token', res.data)
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_retrieve_user_unauthorized(self):
        """Test that authentication is required for users"""
        res =  self.client.post(ME_URL)

        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
Пример #52
0
class PrivateRecipeAPITest(TestCase):
    """ Test authenticated recipe API access """

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

    def retreve_recipes(self):
        """ Testing reteving recipes """
        sample_recepe(user=self.user)
        sample_recepe(user=self.user)

        res = self.client.get(RECIPE_URL)
        recipes = Recipe.objects.all().order_by('-id')
        serializer = RecipeSerializer(recipes, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_recipes_are_limited_to_user(self):
        """ Test recipes are only returns according to the user """

        user2 = get_user_model().objects.create_user(
            '*****@*****.**',
            'testpass'
        )
        sample_recepe(user=user2)
        sample_recepe(user=self.user)
        res = self.client.get(RECIPE_URL)

        recipes = Recipe.objects.filter(user=self.user)
        serializer = RecipeSerializer(recipes, many=True)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        self.assertEqual(res.data, serializer.data)

    def test_view_recipe_details(self):
        """ Test viewving a recipe detail """
        recipe = sample_recepe(user=self.user)
        recipe.tags.add(sampe_tag(user=self.user))
        recipe.ingreedient.add(sampe_ingreedient(self.user))

        url = detail_url(recipe.id)
        res = self.client.get(url)

        serializer = RecipeDetailSerializer(recipe)
        self.assertEqual(res.data, serializer.data)

    def test_create_basic_recipe(self):
        """ Test creating recipe """
        paylaod = {
            "title": "Chocolate cheesecake",
            "time_miniutes": 30,
            "price": 5.00
        }

        res = self.client.post(RECIPE_URL, paylaod)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        for key in paylaod.keys():
            self.assertEqual(paylaod[key], getattr(recipe, key))

    def test_create_recipe_with_tags(self):
        """ Test creating recipe with tags  """
        tag1 = sampe_tag(user=self.user, name='Vegan')
        tag2 = sampe_tag(user=self.user, name='Dessart')

        payload = {
            'title': 'Avacado lime cheesecake',
            'tags': [tag1.id, tag2.id],
            'time_miniutes': 60,
            'price': 20.00
        }

        res = self.client.post(RECIPE_URL, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        tags = recipe.tags.all()
        self.assertEqual(tags.count(), 2)
        self.assertIn(tag1, tags)
        self.assertIn(tag2, tags)

    def test_create_recipe_with_ingreedients(self):
        """ Test creating recipe with ingreedients """
        Ingreedient1 = sampe_ingreedient(user=self.user, name='Prawns')
        Ingreedient2 = sampe_ingreedient(user=self.user, name='Ginger')
        payload = {
            'title': 'Thai prawn red curry',
            'ingreedient': [Ingreedient1.id, Ingreedient2.id],
            'time_miniutes': 20,
            'price': 7.00
        }

        res = self.client.post(RECIPE_URL, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingreedient = recipe.ingreedient.all()
        self.assertEqual(ingreedient.count(), 2)
        self.assertIn(Ingreedient1, ingreedient)
        self.assertIn(Ingreedient2, ingreedient)

    def test_partial_update_recipe(self):
        """ Test updateing recipe with patch """
        recipe = sample_recepe(user=self.user)
        recipe.tags.add(sampe_tag(user=self.user))
        new_tag = sampe_tag(user=self.user, name='Curry')

        payload = {
            'title': 'Chicken tikka',
            'tags': [new_tag.id]
        }

        url = detail_url(recipe.id)
        self.client.patch(url, payload)

        recipe.refresh_from_db()
        self.assertEqual(recipe.title, payload['title'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 1)
        self.assertIn(new_tag, tags)

    def test_full_update(self):
        """ Test update recipe with put """
        recipe = sample_recepe(user=self.user)
        recipe.tags.add(sampe_tag(user=self.user))

        payload = {
            'title': 'Spagehetti carbonara',
            'time_miniutes': 25,
            'price': 5.00
        }

        url = detail_url(recipe.id)
        self.client.put(url, payload)

        recipe.refresh_from_db()
        self.assertEqual(recipe.title, payload['title'])
        self.assertEqual(recipe.time_miniutes, payload['time_miniutes'])
        self.assertEqual(recipe.price, payload['price'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 0)
Пример #53
0
class PrivateIngredientsApiTests(TestCase):
    """Test the private ingredients API"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            "*****@*****.**", "password123")
        self.client.force_authenticate(self.user)

    def test_retrieve_ingredient_list(self):
        """Test retrieving a list of ingredients"""
        Ingredient.objects.create(user=self.user, name="Kale")
        Ingredient.objects.create(user=self.user, name="Salt")

        res = self.client.get(INGREDIENTS_URL)

        ingredients = Ingredient.objects.all().order_by("-name")
        serializer = IngredientSerializer(ingredients, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_ingredients_limited_to_user(self):
        """Test that ingredients for the authenticated user are returned"""
        user2 = get_user_model().objects.create_user("*****@*****.**",
                                                     "password456")
        Ingredient.objects.create(user=user2, name="Vinegar")
        ingredient = Ingredient.objects.create(user=self.user, name="Tumeric")

        res = self.client.get(INGREDIENTS_URL)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 1)
        self.assertEqual(res.data[0]["name"], ingredient.name)

    def test_create_ingredient_successful(self):
        """Test create a new ingredient"""
        payload = {"name": "Cabbage"}
        self.client.post(INGREDIENTS_URL, payload)

        exists = Ingredient.objects.filter(
            user=self.user,
            name=payload["name"],
        ).exists()
        self.assertTrue(exists)

    def test_create_ingredient_invalid(self):
        """Test creating invalid ingredient fails"""
        payload = {"name": ""}
        res = self.client.post(INGREDIENTS_URL, payload)

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

    def test_retrieve_ingredients_assigned_to_recipes(self):
        """Test filtering ingredients by those assigned to recipes"""
        ingredient1 = Ingredient.objects.create(user=self.user, name="Apples")
        ingredient2 = Ingredient.objects.create(user=self.user, name="Turkey")
        recipe = Recipe.objects.create(title="Apple crumble",
                                       time_minutes=5,
                                       price=10,
                                       user=self.user)
        recipe.ingredients.add(ingredient1)

        res = self.client.get(INGREDIENTS_URL, {"assigned_only": 1})

        serializer1 = IngredientSerializer(ingredient1)
        serializer2 = IngredientSerializer(ingredient2)
        self.assertIn(serializer1.data, res.data)
        self.assertNotIn(serializer2.data, res.data)

    def test_retrieve_ingredients_assigned_unique(self):
        """Test filtering ingredients by assigned returns unique items"""
        ingredient = Ingredient.objects.create(user=self.user, name="Eggs")
        Ingredient.objects.create(user=self.user, name="Cheese")
        recipe1 = Recipe.objects.create(title="Eggs benedict",
                                        time_minutes=30,
                                        price=12.00,
                                        user=self.user)
        recipe1.ingredients.add(ingredient)
        recipe2 = Recipe.objects.create(title="Coriander eggs on toast",
                                        time_minutes=20,
                                        price=5.00,
                                        user=self.user)
        recipe2.ingredients.add(ingredient)

        res = self.client.get(INGREDIENTS_URL, {"assigned_only": 1})

        self.assertEqual(len(res.data), 1)
def populate(request):
    password = "******"
    user = User(username="******")
    user.set_password(password)
    user.save()
    request_authenticated = APIRequestFactory()
    request_authenticated.user = user
    participant1 = Participant.objects.create(id=user.id)
    client_authenticated = APIClient()
    client_authenticated.login(username=user.username, password=password)
    client_unauthenticated = APIClient()
    # we create participants
    user2 = User(username="******")
    user2.set_password(password)
    user2.save()
    user3 = User(username="******")
    user3.set_password(password)
    user3.save()
    user4 = User(username="******")
    user4.set_password(password)
    user4.save()
    user5 = User(username="******")
    user5.set_password(password)
    user5.save()
    user6 = User(username="******")
    user6.set_password(password)
    user6.save()
    participant2 = Participant.objects.create(id=user2.id)
    participant3 = Participant.objects.create(id=user3.id)
    # we create a thread where all users are in
    thread1 = Thread.objects.create(name="All in!")
    participation1 = Participation.objects.create(participant=participant1, thread=thread1)
    participation2 = Participation.objects.create(participant=participant2, thread=thread1)
    participation3 = Participation.objects.create(participant=participant3, thread=thread1)
    # we create a thread where all users where in but one has left
    thread2 = Thread.objects.create(name="One has left")
    Participation.objects.create(participant=participant1, thread=thread2)
    Participation.objects.create(participant=participant2, thread=thread2)
    Participation.objects.create(participant=participant3, thread=thread2, date_left=now())
    # we create a thread where all only two users are in
    thread3 = Thread.objects.create(name="Two only are in")
    p1 = Participation.objects.create(participant=participant1, thread=thread3)
    p2 = Participation.objects.create(participant=participant3, thread=thread3)
    # we create a parasiting thread with people unrelated, to ensure it does not modify the counts
    participant4 = Participant.objects.create(id=4)
    participant5 = Participant.objects.create(id=5)
    participant6 = Participant.objects.create(id=6)
    thread_unrelated = Thread.objects.create(name="Unrelated")
    Participation.objects.create(participant=participant4, thread=thread_unrelated)
    Participation.objects.create(participant=participant5, thread=thread_unrelated)
    Participation.objects.create(participant=participant6, thread=thread_unrelated)
    # we map the users and the participants
    dct = dict()
    for u in User.objects.all():
        for p in Participant.objects.all():
            if u.id == p.id:
                dct[p.id] = u
    # 1 message for thread 1, 2 for thread 2, etc.
    # we create messages for each conversation
    messages = []
    for thread in Thread.objects.all():
        participants = [participation.participant for participation in Participation.objects.filter(thread=thread)]
        for i in range(0, 150):
            participant = random.choice(participants)
            messages.append(Message(sender=participant, thread=thread, body="Message by participant {0} in thread {1}".format(dct[participant.id].username, thread.id)))
    Message.objects.bulk_create(messages)
    # a notification check
    # participant 1 has checked his notifications one day ago
    NotificationCheck.objects.create(participant=participant1, date_check=now() - timedelta(days=1))
    # we mark some threads as read
    # participant 3 has read the 2 last messages, 1 only the first
    p2.date_last_check = now() - timedelta(days=1)
    p2.save()
    p1.date_last_check = now() - timedelta(days=2)
    p1.save()
Пример #55
0
class PantryViewTest(APITestCase):
    def setUp(self):
        self.client = APIClient()

        # Set up user data...
        self.user = User.objects.create_user(
            first_name='Jason',
            last_name='Parent',
            email='*****@*****.**',
            username='******',
            password='******'
        )

        # Create unit of measure...
        self.unit_of_measure = UnitOfMeasure.objects.create(description='quantity', abbreviation='qty')

        # Set up food data...
        self.food = Food.objects.create(name='tomatoes')
        self.food_category = FoodCategory.objects.create(description='vegetable')
        FoodCategoryClassification.objects.create(
            food=self.food, food_category=self.food_category
        )

        # Set up pantry data...
        self.pantry = Pantry.objects.create(name='Home')
        UserPantry.objects.create(user=self.user, pantry=self.pantry)
        PantryFood.objects.create(pantry=self.pantry, food=self.food)

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

    def test_can_create_user_pantries(self):
        with self.assertNumQueries(7):
            response = self.client.post('/api/v1/recipes/pantries/', {
                'name': 'New'
            })

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

        user_pantry = UserPantry.objects.get(user=self.user, pantry__name='New')

        self.assertEqual(response.data, {
            'pantries': [{
                'id': self.pantry.id,
                'name': 'Home',
                'foods': [f.id for f in self.pantry.foods.all()]
            }, {
                'id': user_pantry.pantry.id,
                'name': user_pantry.pantry.name,
                'foods': [f.id for f in user_pantry.pantry.foods.all()]
            }]
        })

    def test_can_retrieve_user_pantries(self):
        with self.assertNumQueries(5):
            response = self.client.get('/api/v1/recipes/pantries/')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'pantries': [{
                'id': self.pantry.id,
                'name': self.pantry.name,
                'foods': [f.id for f in self.pantry.foods.all()]
            }]
        })

    def test_new_user_has_pantry(self):
        user_pantries = UserPantry.objects.filter(user=self.user)

        for u in user_pantries:
            u.pantry.delete()
            u.delete()

        with self.assertNumQueries(6):
            response = self.client.get('/api/v1/recipes/pantries/')

        user_pantry = UserPantry.objects.get(user=self.user)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'pantries': [{
                'id': user_pantry.pantry.id,
                'name': user_pantry.pantry.name,
                'foods': [f.id for f in user_pantry.pantry.foods.all()]
            }]
        })

    def test_can_create_user_pantry_foods(self):
        # Create a new food...
        food = Food.objects.create(name='white onions')

        # Add the food to the pantry...
        with self.assertNumQueries(7):
            response = self.client.post('/api/v1/recipes/pantries/{pantry_id}/foods/{food_id}/'.format(
                pantry_id=self.pantry.id, food_id=food.id
            ), {
                'amount': 1.00,
                'unit_of_measure': self.unit_of_measure.id
            })

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(PantryFood.objects.filter(pantry=self.pantry, food=food).exists())

    def test_can_update_user_pantry_foods(self):
        # Create a new food...
        food = Food.objects.create(name='white onions')
        PantryFood.objects.create(pantry=self.pantry, food=food)

        # Add the food to the pantry...
        with self.assertNumQueries(7):
            response = self.client.put('/api/v1/recipes/pantries/{pantry_id}/foods/{food_id}/'.format(
                pantry_id=self.pantry.id, food_id=food.id
            ), {
                'amount': 2.00,
                'unit_of_measure': self.unit_of_measure.id
            })

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(PantryFood.objects.filter(pantry=self.pantry, food=food).exists())

    def test_can_delete_user_pantry_foods(self):
        # Add a new food to the pantry...
        food = Food.objects.create(name='white onions')
        PantryFood.objects.create(pantry=self.pantry, food=food)

        # Delete the food from the pantry...
        with self.assertNumQueries(5):
            response = self.client.delete('/api/v1/recipes/pantries/{pantry_id}/foods/{food_id}/'.format(
                pantry_id=self.pantry.id, food_id=food.id
            ))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertFalse(PantryFood.objects.filter(pantry=self.pantry, food=food).exists())
Пример #56
0
 def setUp(self):
     self.client = APIClient()
     self.user = get_user_model().objects.create_user(
         "*****@*****.**", "password123")
     self.client.force_authenticate(self.user)
Пример #57
0
class RecipeViewTest(APITestCase):
    def setUp(self):
        self.client = APIClient()

        # Set up food data...
        self.food = Food.objects.create(name='tomatoes')
        self.food_category = FoodCategory.objects.create(description='vegetable')
        FoodCategoryClassification.objects.create(
            food=self.food, food_category=self.food_category
        )

        # Set up recipe data...
        self.recipe = Recipe.objects.create(
            name='Essential Simmered Tomato-Jalapeno Sauce',
            description='Sample description...',
            instructions='Sample instructions...'
        )
        self.recipe_category = RecipeCategory.objects.create(description='salsa')
        RecipeCategoryClassification.objects.create(
            recipe=self.recipe, recipe_category=self.recipe_category
        )
        Ingredient.objects.create(recipe=self.recipe, food=self.food)

    def test_cannot_retrieve_nonexistent_recipe(self):
        with self.assertNumQueries(1):
            response = self.client.get('/api/v1/recipes/recipes/0/')

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

    def test_can_retrieve_recipe(self):
        with self.assertNumQueries(3):
            response = self.client.get('/api/v1/recipes/recipes/{}/'.format(self.recipe.pk))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'recipes': [{
                'id': self.recipe.id,
                'name': self.recipe.name,
                'description': self.recipe.description,
                'instructions': self.recipe.instructions,
                'foods': [f.id for f in self.recipe.foods.all()],
                'categories': [c.id for c in self.recipe.categories.all()]
            }]
        })

    def test_can_retrieve_basic_recipe_list(self):
        with self.assertNumQueries(4):
            response = self.client.get('/api/v1/recipes/recipes/')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'recipes': [{
                'id': self.recipe.id,
                'name': self.recipe.name,
                'foods': [f.id for f in self.recipe.foods.all()],
                'categories': [c.id for c in self.recipe.categories.all()]
            }]
        })

    def test_can_retrieve_basic_recipe_list_with_categories(self):
        with self.assertNumQueries(4):
            response = self.client.get('/api/v1/recipes/recipes/?categories=true')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'recipes': [{
                'id': self.recipe.id,
                'name': self.recipe.name,
                'foods': [f.id for f in self.recipe.foods.all()],
                'categories': [c.id for c in self.recipe.categories.all()]
            }],
            'recipe_categories': [{
                'id': self.recipe_category.id,
                'description': self.recipe_category.description
            }]
        })

    def test_can_retrieve_basic_recipe_list_with_foods(self):
        with self.assertNumQueries(5):
            response = self.client.get('/api/v1/recipes/recipes/?foods=true')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'recipes': [{
                'id': self.recipe.id,
                'name': self.recipe.name,
                'foods': [f.id for f in self.recipe.foods.all()],
                'categories': [c.id for c in self.recipe.categories.all()]
            }],
            'foods': [{
                'id': self.food.id,
                'name': self.food.name,
                'categories': [c.id for c in self.food.categories.all()],
                'count': 1
            }]
        })

    def test_can_retrieve_basic_recipe_list_with_categories_and_foods(self):
        with self.assertNumQueries(5):
            response = self.client.get('/api/v1/recipes/recipes/?categories=true&foods=true')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'recipes': [{
                'id': self.recipe.id,
                'name': self.recipe.name,
                'foods': [f.id for f in self.recipe.foods.all()],
                'categories': [c.id for c in self.recipe.categories.all()]
            }],
            'recipe_categories': [{
                'id': self.recipe_category.id,
                'description': self.recipe_category.description
            }],
            'foods': [{
                'id': self.food.id,
                'name': self.food.name,
                'categories': [c.id for c in self.food.categories.all()],
                'count': 1
            }],
            'food_categories': [{
                'id': self.food_category.id,
                'description': self.food_category.description
            }]
        })
Пример #58
0
 def setUp(self):
     self.user = create_user(email='*****@*****.**',
                             password='******',
                             name='name')
     self.client = APIClient()
     self.client.force_authenticate(user=self.user)
Пример #59
0
class DRFTestCase(TestCase):
    if "django.contrib.sites" in settings.INSTALLED_APPS:
        fixtures = ["sites.json"]

    @classmethod
    def setUpTestData(cls):
        super(DRFTestCase, cls).setUpTestData()

        cls.user_model = get_user_model()

        # Superuser
        cls.superuser = cls.user_model.objects.create(
            username="******",
            email="*****@*****.**",
            is_superuser=True,
            is_staff=True
        )
        cls.superuser.set_password("password")
        cls.superuser.save()

        # Staff
        cls.staff = cls.user_model.objects.create(
            username="******",
            email="*****@*****.**",
            is_staff=True
        )
        cls.staff.set_password("password")
        cls.staff.save()

        # Plain user
        cls.user = cls.user_model.objects.create(
            username="******",
            email="*****@*****.**"
        )
        cls.user.set_password("password")
        cls.user.save()

    def setUp(self):
        super(DRFTestCase, self).setUp()
        self.factory = APIRequestFactory()
        self.client = APIClient()
        self.client.logout()
        self.one = DummyModel.objects.create(title="One", code="one")
        self.two = DummyModel.objects.create(title="Two", code="two")

    def tearDown(self):
        self.client.logout()
        DummyModel.objects.all().delete()
        super(DRFTestCase, self).tearDown()

    def test_get_dummymodels(self):
        response = self.client.get("/api/dummies/")
        as_json_1 = response.json()

        # Drop to low level API so post_save does not trigger, meaning the
        # cached version is fetched on the next request.
        DummyModel.objects.filter(pk=self.one.pk).update(title="Onae")
        response = self.client.get("/api/dummies/")
        as_json_2 = response.json()
        self.assertEqual(as_json_1, as_json_2)

        # Modify it the normal way, which removes the item from cache.
        self.one.title = "Onbe"
        self.one.save()
        response = self.client.get("/api/dummies/")
        as_json_3 = response.json()
        self.assertNotEqual(as_json_1, as_json_3)

        # Trivial fetch to prove it is cached now
        response = self.client.get("/api/dummies/")
        as_json_4 = response.json()
        self.assertEqual(as_json_3, as_json_4)

        # Modify via API to confirm that post_save is fired implicitly
        data = {
            "title": "Onze"
        }
        response = self.client.patch("/api/dummies/%s/" % self.one.pk, data)
        response = self.client.get("/api/dummies/")
        as_json_5 = response.json()
        self.assertNotEqual(as_json_4, as_json_5)

        # Add an evaluate parameter which leads to a cache miss. Also
        # surreptiously edit the object so we can confirm a cache miss.
        DummyModel.objects.filter(pk=self.one.pk).update(title="Once")
        di = copy.deepcopy(settings.ULTRACACHE)
        di["drf"] = {"viewsets": {"*": {"evaluate": "request.user.is_anonymous"}}}
        with override_settings(ULTRACACHE=di):
            response = self.client.get("/api/dummies/")
            as_json_6 = response.json()
            self.assertNotEqual(as_json_5, as_json_6)

        # Trivial fetch to refresh the cache
        response = self.client.get("/api/dummies/")
        as_json_7 = response.json()

        # Disable viewset caching which leads to a cache miss. Also
        # surreptiously edit the object so we can confirm a cache miss.
        DummyModel.objects.filter(pk=self.one.pk).update(title="Onde")
        di = copy.deepcopy(settings.ULTRACACHE)
        di["drf"] = {"viewsets": {object: {}}}
        with override_settings(ULTRACACHE=di):
            response = self.client.get("/api/dummies/")
            as_json_8 = response.json()
            self.assertNotEqual(as_json_7, as_json_8)

        # Trivial fetch to refresh the cache
        response = self.client.get("/api/dummies/")
        as_json_9 = response.json()

        # Enable viewset caching for a single viewset class. Also
        # surreptiously edit the object so we can confirm a cache hit.
        DummyModel.objects.filter(pk=self.one.pk).update(title="Onee")
        di = copy.deepcopy(settings.ULTRACACHE)
        di["drf"] = {"viewsets": {DummyViewSet: {}}}
        with override_settings(ULTRACACHE=di):
            response = self.client.get("/api/dummies/")
            as_json_10 = response.json()
            self.assertEqual(as_json_9, as_json_10)

    def test_get_dummymodel(self):
        url = "/api/dummies/%s/" % self.one.pk
        response = self.client.get(url)
        as_json_1 = response.json()

        # Drop to low level API so post_save does not trigger, meaning the
        # cached version is fetched on the next request.
        DummyModel.objects.filter(pk=self.one.pk).update(title="Onfe")
        response = self.client.get(url)
        as_json_2 = response.json()
        self.assertEqual(as_json_1, as_json_2)

        # Modify it the normal way, which removes the item from cache.
        self.one.title = "Onge"
        self.one.save()
        response = self.client.get(url)
        as_json_3 = response.json()
        self.assertNotEqual(as_json_1, as_json_3)
Пример #60
0
    def setUp(self):
        self.client = APIClient()

        # Set up units of measure...
        self.unit_of_measure = UnitOfMeasure.objects.create(description='teaspoons', abbreviation='tsp')