def test_put_verify_job(webapp, test_repository, test_job, text_summary_lines, test_user,
                        failure_classifications):
    client = APIClient()
    client.force_authenticate(user=test_user)

    TextLogErrorMetadata.objects.filter(text_log_error__step__job=test_job).update(best_is_verified=True)
    FailureLine.objects.filter(job_guid=test_job.guid).update(best_is_verified=True)

    text_summary_lines = TextLogSummary.objects.filter(job_guid=test_job.guid).get().lines.all()
    assert len(text_summary_lines) > 0
    data = [{"id": item.id, "bug_number": i + 1, "verified": True} for
            i, item in enumerate(text_summary_lines)]

    resp = client.put(reverse("text-log-summary-line-list"),
                      data, format="json")

    assert resp.status_code == 200

    assert test_job.is_fully_verified()

    bug_job_items = BugJobMap.objects.filter(job=test_job)
    assert {item.bug_id for item in bug_job_items} == set(range(1, len(text_summary_lines) + 1))
    assert all(item.user == test_user for item in bug_job_items)

    note = JobNote.objects.filter(job=test_job).get()
    assert note.user == test_user
    assert note.failure_classification.name == "intermittent"
Пример #2
0
    def test_update(self, user1, node1):
        client = APIClient()
        client.force_authenticate(user=user1)

        response = client.patch(
            reverse('node-detail', kwargs={"pk": node1.id}),
            data={
                "meta": "different whatever",
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED

        response = client.put(
            reverse('node-detail', kwargs={"pk": node1.id}),
            data={
                "name": "whatever",
                "meta": "different whatever",
                "type": 1,
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_200_OK

        response = client.put(
            reverse('node-detail', kwargs={"pk": 9999}),
            data={
                "name": "whatever",
                "meta": "different whatever",
                "type": 1,
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_404_NOT_FOUND
Пример #3
0
def api_client(user, db):
    """
    A rest_framework api test client not auth'd.
    """
    client = APIClient()
    client.force_authenticate(user=user)
    return client
Пример #4
0
def test_push_cancel_all(failure_classifications,
                         push_with_three_jobs, pulse_action_consumer,
                         test_repository, test_user):
    """
    Issue cancellation of a push with three unfinished jobs.
    """
    client = APIClient()
    client.force_authenticate(user=test_user)

    # Ensure all jobs are pending..
    for job in Job.objects.all():
        assert job.state == 'pending'

    url = reverse("push-cancel-all",
                  kwargs={"project": test_repository.name, "pk": push_with_three_jobs.id})
    client.post(url)

    # Ensure all jobs are cancelled..
    for job in Job.objects.all():
        assert job.state == 'completed'
        assert job.result == 'usercancel'

    for _ in range(0, 3):
        message = pulse_action_consumer.get(block=True, timeout=2)
        content = message.payload

        assert content['action'] == 'cancel'
        assert content['project'] == test_repository.name
Пример #5
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
def test_create_bug_job_map_dup(eleven_jobs_processed, mock_message_broker, jm):
    """
    test creating the same bug map skips it
    """

    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
    )

    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()
def test_alert_summaries_put(webapp, test_repository, test_perf_signature,
                             test_perf_alert_summary, test_user, test_sheriff):
    # verify that we fail if not authenticated
    webapp.put_json(reverse('performance-alert-summaries-list') + '1/', {
        'status': 1
    }, status=403)
    assert PerformanceAlertSummary.objects.get(id=1).status == 0

    # verify that we fail if authenticated, but not staff
    client = APIClient()
    client.force_authenticate(user=test_user)
    resp = client.put(reverse('performance-alert-summaries-list') + '1/', {
        'status': 1
    }, format='json')
    assert resp.status_code == 403
    assert PerformanceAlertSummary.objects.get(id=1).status == 0

    # verify that we succeed if authenticated + staff
    client = APIClient()
    client.force_authenticate(user=test_sheriff)
    resp = client.put(reverse('performance-alert-summaries-list') + '1/', {
        'status': 1
    }, format='json')
    assert resp.status_code == 200
    assert PerformanceAlertSummary.objects.get(id=1).status == 1
Пример #8
0
    def test_update_save_data_by_user(self):
        client = APIClient()
        client.force_authenticate(user=self.user2)

        response_create = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file2.txt'
        })
        response_update1 = client.patch('/save-data/1/', data={
            'saved_file': 'file01.txt'
        }, format='json') # Can not update unless their own
        response_update2 = client.patch('/save-data/4/', data={
            'saved_file': 'file02.txt'
        }, format='json')
        response1 = client.get('/save-data/1/') # Can't read unless their own
        response2 = client.get('/save-data/4/')

        self.assertEqual(response_create.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response_update1.status_code, \
            status.HTTP_404_NOT_FOUND)
        self.assertEqual(response_update2.status_code, status.HTTP_200_OK)
        self.assertEqual(response1.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response2.status_code, status.HTTP_200_OK)
        self.assertEqual(response2.data['id'], 4)
        self.assertEqual(response2.data['saved_file'], 'file02.txt')
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()
Пример #10
0
    def test_read_save_data_by_user(self):
        client = APIClient()
        client.force_authenticate(user=self.user2)

        response_create = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file2.txt'
        })

        response1 = client.get('/save-data/')
        response2 = client.get('/save-data/1/')
        response3 = client.get('/save-data/?game=2')
        response4 = client.get('/save-data/?user=user1')
        response5 = client.get('/save-data/?user=user2')

        self.assertEqual(response_create.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response2.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response3.status_code, status.HTTP_200_OK)
        self.assertEqual(response4.status_code, status.HTTP_200_OK)
        self.assertEqual(response5.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response1.data), 1)
        self.assertEqual(len(response3.data), 0)
        self.assertEqual(len(response4.data), 0)
        self.assertEqual(len(response5.data), 1)
Пример #11
0
    def test_update_save_data_by_operator(self):
        client = APIClient()
        client.force_authenticate(user=self.user1)

        response_create = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file2.txt'
        })
        response_update1 = client.patch('/save-data/1/', data={
            'saved_file': 'file01.txt'
        }, format='json')
        response_update2 = client.patch('/save-data/4/', data={
            'saved_file': 'file02.txt'
        }, format='json')
        response1 = client.get('/save-data/1/')
        response2 = client.get('/save-data/4/')

        self.assertEqual(response_create.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response_update1.status_code, status.HTTP_200_OK)
        self.assertEqual(response_update2.status_code, status.HTTP_200_OK)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response2.status_code, status.HTTP_200_OK)
        self.assertEqual(response1.data['id'], 1)
        self.assertEqual(response1.data['saved_file'], 'file01.txt')
        self.assertEqual(response2.data['id'], 4)
        self.assertEqual(response2.data['saved_file'], 'file02.txt')
Пример #12
0
    def test_create_save_data_by_operator(self):
        client = APIClient()
        client.force_authenticate(user=self.user1)

        response_create1 = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file1.txt'
        })
        response_create2 = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file2.txt'
        })
        response1 = client.get('/save-data/')
        response2 = client.get('/save-data/?game=3')

        self.assertEqual(response_create1.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response_create2.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response1.data), 5)
        self.assertEqual(len(response2.data), 2)
Пример #13
0
    def test_create_save_data_by_user(self):
        client = APIClient()
        client.force_authenticate(user=self.user2)

        response_create1 = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file1.txt'
        }) # Access denied, can only create own
        response_create2 = client.post('/save-data/', data={
            'user': '******',
            'game': '3',
            'saved_file': 'file2.txt'
        })
        response1 = client.get('/save-data/')
        response2 = client.get('/save-data/?game=3')

        self.assertEqual(response_create1.status_code, \
            status.HTTP_403_FORBIDDEN)
        self.assertEqual(response_create2.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response1.data), 1)
        self.assertEqual(len(response2.data), 1)
Пример #14
0
    def test_read_game_session_by_user(self):
        client1 = APIClient()
        client1.force_authenticate(user=self.user1)
        client2 = APIClient()
        client2.force_authenticate(user=self.user2)

        # Joins game
        response_create1 = client1.post('/game-session/', data={
            'user': '******',
            'game': self.game2.id
        }, format='json')
        response_create2 = client1.post('/game-session/', data={
            'user': '******',
            'game': self.game1.id
        }, format='json')
        # Read Game Session
        response1 = client2.get('/game-session/')
        response2 = client2.get('/game-session/?game=1')
        response3 = client2.get('/game-session/?user=user1')
        response4 = client2.get('/game-session/?user=user2')
        response5 = client2.get('/game-session/1/')
        response6 = client2.get('/game-session/2/')

        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response2.status_code, status.HTTP_200_OK)
        self.assertEqual(response3.status_code, status.HTTP_200_OK)
        self.assertEqual(response4.status_code, status.HTTP_200_OK)
        self.assertEqual(response5.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response6.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response1.data), 1)
        self.assertEqual(len(response2.data), 1)
        self.assertEqual(len(response3.data), 0)
        self.assertEqual(len(response4.data), 1)
        self.assertEqual(response6.data['id'], 2)
Пример #15
0
    def test_update_game_session(self):
        client = APIClient()
        client.force_authenticate(user=self.user1)

        # Joins game
        response_create1 = client.post('/game-session/', data={
            'user': '******',
            'game': self.game2.id
        }, format='json')
        response_create2 = client.post('/game-session/', data={
            'user': '******',
            'game': self.game1.id
        }, format='json')
        # Update game
        response_update1 = client.patch('/game-session/1/', data={
            'game':self.game2.id
        }, format='json')
        response_update2 = client.patch('/game-ownership/2/', data={
            'controller': 100
        }, format='json')

        self.assertEqual(response_create1.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response_create2.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response_update1.status_code, \
            status.HTTP_403_FORBIDDEN)
        self.assertEqual(response_update2.status_code, \
            status.HTTP_403_FORBIDDEN)
Пример #16
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()))
Пример #17
0
    def test_buy_game_by_operator(self):
        client = APIClient()
        client.force_authenticate(user=self.user1)

        response_create1 = client.post('/game-ownership/', data={
            'user': self.user1.username,
            'game': self.game1.id
        }, format='json') # Duplicate
        response_create2 = client.post('/game-ownership/', data={
            'user': self.user1.username,
            'game': self.game3.id
        }, format='json')
        response_create3 = client.post('/game-ownership/', data={
            'user': self.user2.username,
            'game': self.game3.id
        }, format='json')
        response1 = client.get('/game-ownership/')
        response2 = client.get('/game-ownership/?user=user1')
        response3 = client.get('/game-ownership/?user=user2')
        response4 = client.get('/game-ownership/?game=3')
        
        self.assertEqual(response_create1.status_code, \
            status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response_create2.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response_create3.status_code, \
            status.HTTP_201_CREATED)
        self.assertEqual(response1.status_code, status.HTTP_200_OK)
        self.assertEqual(response2.status_code, status.HTTP_200_OK)
        self.assertEqual(response3.status_code, status.HTTP_200_OK)
        self.assertEqual(response4.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response1.data), 5)
        self.assertEqual(len(response2.data), 3)
        self.assertEqual(len(response3.data), 2)
        self.assertEqual(len(response4.data), 2)
Пример #18
0
def test_put_duplicate_multiple_repeated(webapp, classified_failures, test_user):
    client = APIClient()
    client.force_authenticate(user=test_user)

    new = ClassifiedFailure(bug_number=1234)
    new.save()
    classified_failures.append(new)

    client.put(reverse("classified-failure-list"),
               [{"id": classified_failures[0].id, "bug_number": 1234}],
               format="json")
    new_classified_failures = ClassifiedFailure.objects.all()
    assert [item.id for item in new_classified_failures] == [2, 3]
    assert [item.bug_number for item in new_classified_failures] == [None, 1234]
    resp = client.put(reverse("classified-failure-list"),
                      [{"id": classified_failures[0].id, "bug_number": 1234},
                       {"id": classified_failures[1].id, "bug_number": 1234}],
                      format="json")

    actual = resp.data
    assert len(actual) == 2
    expected = [{"id": new.id,
                 "bug_number": 1234,
                 "bug": None},
                {"id": new.id,
                 "bug_number": 1234,
                 "bug": None}]
    assert actual == expected
Пример #19
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
Пример #20
0
def test_put_multiple_repeat(webapp, classified_failures, test_user):
    client = APIClient()
    client.force_authenticate(user=test_user)

    classified_failures[0].bug_number = 1234
    classified_failures[0].save()

    resp = client.put(reverse("classified-failure-list"),
                      [{"id": classified_failures[0].id, "bug_number": 1234},
                       {"id": classified_failures[1].id, "bug_number": 5678}],
                      format="json")

    assert resp.status_code == 200

    actual = resp.data
    assert len(actual) == 2
    expected = [{"id": classified_failures[0].id,
                 "bug_number": 1234,
                 "bug": None},
                {"id": classified_failures[1].id,
                 "bug_number": 5678,
                 "bug": None}]
    assert actual == expected

    classified_failures[0].refresh_from_db()
    assert classified_failures[0].bug_number == 1234
    classified_failures[1].refresh_from_db()
    assert classified_failures[1].bug_number == 5678
Пример #21
0
def test_put_multiple_duplicate(webapp, classified_failures, test_user):
    client = APIClient()
    client.force_authenticate(user=test_user)

    new = ClassifiedFailure(bug_number=1234)
    new.save()
    classified_failures.append(new)

    resp = client.put(reverse("classified-failure-list"),
                      [{"id": classified_failures[0].id, "bug_number": 1234},
                       {"id": classified_failures[1].id, "bug_number": 5678}],
                      format="json")

    actual = resp.data
    assert len(actual) == 2
    expected = [{"id": classified_failures[2].id,
                 "bug_number": 1234,
                 "bug": None},
                {"id": classified_failures[1].id,
                 "bug_number": 5678,
                 "bug": None}]
    assert actual == expected

    new_classified_failures = ClassifiedFailure.objects.all()
    assert len(new_classified_failures) == len(classified_failures) - 1
Пример #22
0
class UserModelTests(TestCase):
    def setUp(self):
        self.client = APIClient()
        # create users
        self.user1 = User.objects.create(username='******', password='******', email="*****@*****.**", is_active=True)
        self.user1.save()
        self.user2 = User.objects.create(username='******', password='******', email="*****@*****.**", is_active=False)
        self.user2.save()

    def test_login_success(self):
        response = self.client.post('/login/', {'username': '******', 'password': '******'}, format='json')
        self.assertEqual(response.status_code, 200)

    def test_login_fail_user_inactive(self):
        response = self.client.post('/login/', {'username': '******', 'password': '******'}, format='json')
        self.assertEquals(response.status_code, 200)

    def test_login_fail_user_not_exist(self):
        response = self.client.post('/login/', {'username': '******', 'password': '******'}, format='json')
        print(response.content)
        self.assertEquals(response.status_code, 200)

    def test_login_fail_incorrect_password(self):
        response = self.client.post('/login/', {'username': '******', 'password': '******'}, format='json')
        self.assertTrue(response.status_code == 200)

    def test_logout(self):
        # authenticate before logout
        self.client.force_authenticate(user=self.user1)
        response = self.client.post('/logout/')
        self.assertTrue(response.status_code == 200)
Пример #23
0
def synchronized_daily(request):
    data = []
    labels = []
    chart_data = {}

    client = APIClient()
    client.force_authenticate(user=request.user)
    response = client.get(
        '/api/v1/token/stats/syncs/daily/',
        HTTP_ACCEPT_LANGUAGE=request.LANGUAGE_CODE
    )

    if hasattr(response, 'data') and response.status_code == status.HTTP_200_OK:
        labels, data = zip(*response.data)

    chart_data[_('Computers')] = list(data)

    return render(
        request,
        'includes/spline_js.html',
        {
            'data': chart_data,
            'x_labels': list(labels),
            'id': 'syncs-daily',
        }
    )
Пример #24
0
def test_update_failure_line_ignore(eleven_jobs_stored, jm, failure_lines,
                                    classified_failures, test_user):

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

    MatcherManager.register_detector(ManualDetector)

    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": None}

    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 is None
    assert failure_line.best_is_verified
Пример #25
0
def synchronized_monthly(request):
    labels = {
        'total': _("Totals")
    }
    x_labels = {}
    data = {}
    new_data = {}
    total = []
    chart_data = {}

    delta = relativedelta(months=+1)
    end_date = date.today() + delta
    begin_date = end_date - relativedelta(months=+MONTHLY_RANGE)

    client = APIClient()
    client.force_authenticate(user=request.user)
    url = '/api/v1/token/stats/syncs/monthly/'

    platforms = Platform.objects.only("id", "name")
    for platform in platforms:
        new_data[platform.id] = []
        labels[platform.id] = platform.name

        response = client.get(
            '{}?platform_id={}'.format(url, platform.id),
            HTTP_ACCEPT_LANGUAGE=request.LANGUAGE_CODE
        )
        if hasattr(response, 'data') and response.status_code == status.HTTP_200_OK:
            x_labels[platform.id], data[platform.id] = zip(*response.data)

    # shuffle data series
    x_axe = []
    for monthly in month_year_iter(
        begin_date.month, begin_date.year,
        end_date.month, end_date.year
    ):
        key = '%d-%02d' % (monthly[0], monthly[1])
        x_axe.append(key)
        total_month = 0
        for serie in data:
            new_data[serie].append(
                data[serie][x_labels[serie].index(key)] if key in x_labels[serie] else 0
            )
            total_month += new_data[serie][-1]

        total.append(total_month)

    chart_data[labels['total']] = total
    for item in new_data:
        chart_data[labels[item]] = new_data[item]

    return render(
        request,
        'includes/spline_js.html',
        {
            'data': chart_data,
            'x_labels': x_axe,
            'id': 'syncs-monthly',
        }
    )
    def test_create_chapter_fail(self, registered_users):
        # create client
        client = APIClient()
        client.force_authenticate(user=registered_users['bob'])

        # create book via api
        book_title = fake.name()
        response = client.post(
            reverse("v1:book-list"),
            data={
                'title': book_title,
                'language_id': 1,
                'owner_id': registered_users['bob'].id
            }
        )
        book_id = response.data['id']

        assert response.data['title'] == book_title

        # create chapter
        response = client.post(
            reverse("v1:editor_chapter_list_create_api", kwargs={'pk': book_id}),
        )

        assert response.status_code is status.HTTP_400_BAD_REQUEST

        chapter_title = fake.name()
        response = client.post(
            reverse("v1:editor_chapter_list_create_api", kwargs={'pk': book_id}),
            data={'asdasd': chapter_title}
        )

        assert response.status_code is status.HTTP_400_BAD_REQUEST
Пример #27
0
def test_job_cancel_authorized(webapp, test_repository, eleven_jobs_stored,
                               pulse_action_consumer, test_user):
    """
    Validate that job gets updated when a valid user hits this endpoint.
    """
    client = APIClient()
    client.force_authenticate(user=test_user)

    # get the job, set its state to pending
    job = Job.objects.get(id=1)
    job.state = 'pending'
    job.save()

    url = reverse("jobs-cancel",
                  kwargs={"project": test_repository.name})
    client.post(url, {"job_id_list": [job.id]})

    message = pulse_action_consumer.get(block=True, timeout=2)
    content = message.payload

    assert content['project'] == test_repository.name
    assert content['action'] == 'cancel'
    assert content['job_guid'] == job.guid
    assert content['requester'] == test_user.email

    # validate that we modified the job structure appropriately
    old_last_modified = job.last_modified
    job.refresh_from_db()
    assert old_last_modified < job.last_modified
    assert job.result == 'usercancel'
def test_put_multiple(webapp, text_summary_lines, test_user):
    client = APIClient()
    client.force_authenticate(user=test_user)

    text_summary_lines[0].bug_number = 1234
    text_summary_lines[0].save()

    resp = client.put(reverse("text-log-summary-line-list"),
                      [{"id": text_summary_lines[0].id, "bug_number": 5678, "verified": True},
                       {"id": text_summary_lines[1].id, "bug_number": 9012, "verified": True}],
                      format="json")

    assert resp.status_code == 200

    actual = resp.data
    expected = [{"id": text_summary_lines[0].id,
                 "summary": text_summary_lines[0].summary.id,
                 "line_number": text_summary_lines[0].line_number,
                 "failure_line": text_summary_lines[0].failure_line.id,
                 "bug_number": 5678,
                 "verified": True,
                 "bug": None},
                {"id": text_summary_lines[1].id,
                 "summary": text_summary_lines[1].summary.id,
                 "line_number": text_summary_lines[1].line_number,
                 "failure_line": text_summary_lines[1].failure_line.id,
                 "bug_number": 9012,
                 "verified": True,
                 "bug": None}]
    assert actual == expected

    text_summary_lines[0].refresh_from_db()
    assert text_summary_lines[0].bug_number == 5678
    text_summary_lines[1].refresh_from_db()
    assert text_summary_lines[1].bug_number == 9012
    def test_list_chapters(self, registered_users, books):
        user_bob = registered_users['bob']
        books[0].owner = user_bob

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

        response = client.get(
            reverse("v1:editor_chapter_list_create_api", kwargs={'pk': books[0].id})
        )

        # we got 200 OK
        assert response.status_code is status.HTTP_200_OK
        # we don't have chapters yet
        assert response.data['count'] is 0

        # another book
        response = client.get(
            reverse("v1:editor_chapter_list_create_api", kwargs={'pk': books[1].id})
        )

        # we got 200 OK
        assert response.status_code is status.HTTP_200_OK
        # we don't have chapters yet
        assert response.data['count'] is 0
Пример #30
0
def test_resultset_cancel_all(jm, resultset_with_three_jobs, pulse_action_consumer):
    """
    Issue cancellation of a resultset with three unfinished jobs.
    """
    client = APIClient()
    user = User.objects.create(username="******", email="*****@*****.**")
    client.force_authenticate(user=user)

    # Ensure all jobs are pending..
    jobs = jm.get_job_list(0, 3)
    for job in jobs:
        assert job['state'] == 'pending'

    url = reverse("resultset-cancel-all",
                  kwargs={"project": jm.project, "pk": resultset_with_three_jobs})
    client.post(url)

    # Ensure all jobs are cancelled..
    jobs = jm.get_job_list(0, 3)
    for job in jobs:
        assert job['state'] == 'completed'
        assert job['result'] == 'usercancel'

    for _ in range(0, 3):
        message = pulse_action_consumer.get(block=True, timeout=2)
        content = json.loads(message.body)

        assert content['action'] == 'cancel'
        assert content['project'] == jm.project

    user.delete()
Пример #31
0
class RecipeImageUploadTest(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**',
            'testpass'
        )
        self.client.force_authenticate(self.user)
        self.recipe = sample_recipe(user=self.user)

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

    def test_upload_image_to_recipe(self):
        """Test uploading an image to recipe"""
        url = image_upload_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_request(self):
        """Test uploading an invalid image"""
        url = image_upload_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):
        """Test returning recipes with specific tags"""
        recipe1 = sample_recipe(user=self.user, title='Arepa con webo')
        recipe2 = sample_recipe(user=self.user, title='Avocado toast')
        tag = sample_tag(user=self.user, name='Vegan')
        tag2 = sample_tag(user=self.user, name='Vegetarian')
        recipe1.tags.add(tag)
        recipe2.tags.add(tag2)
        recipe3 = sample_recipe(user=self.user, title='Fish and chips')

        res = self.client.get(
            RECIPE_URLS,
            {'tags': f'{tag.id},{tag2.id}'}
        )
        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)
        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)

    def test_filter_recipe_by_ingredients(self):
        """Test returning recipes with specific ingredients"""
        recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')
        recipe2 = sample_recipe(user=self.user, title='pollo frito')
        ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')
        ingredient2 = sample_ingredient(user=self.user, name='pollo')
        recipe1.ingredient.add(ingredient1)
        recipe2.ingredient.add(ingredient2)
        recipe3 = sample_recipe(user=self.user, title='Steak and mushrooms')

        res = self.client.get(
            RECIPE_URLS,
            {'ingredient': f'{ingredient1.id},{ingredient2.id}'}
        )
        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)
        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3, res.data)
Пример #32
0
class PrivateRecipeApiTests(TestCase):
    """Test authenticated recipe API access"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'testpass')
        self.client.force_authenticate(self.user)

    def test_retrieve_recipes(self):
        """Test retrieving list of recipes"""
        sample_recipe(user=self.user)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPES_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_limited_to_user(self):
        """Test retrieving recipes for user"""
        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'pass')
        sample_recipe(user=user2)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPES_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_detail(self):
        """Test viewing a recipe detail"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        recipe.ingredients.add(sample_ingredient(user=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"""
        payload = {
            'title': 'Test recipe',
            'time_minutes': 30,
            'price': 10.00,
        }
        res = self.client.post(RECIPES_URL, payload)

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

    def test_create_recipe_with_tags(self):
        """Test creating a recipe with tags"""
        tag1 = sample_tag(user=self.user, name='Tag 1')
        tag2 = sample_tag(user=self.user, name='Tag 2')
        payload = {
            'title': 'Test recipe with two tags',
            'tags': [tag1.id, tag2.id],
            'time_minutes': 30,
            'price': 10.00
        }
        res = self.client.post(RECIPES_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_ingredients(self):
        """Test creating recipe with ingredients"""
        ingredient1 = sample_ingredient(user=self.user, name='Ingredient 1')
        ingredient2 = sample_ingredient(user=self.user, name='Ingredient 2')
        payload = {
            'title': 'Test recipe with ingredients',
            'ingredients': [ingredient1.id, ingredient2.id],
            'time_minutes': 45,
            'price': 15.00
        }

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

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingredients = recipe.ingredients.all()
        self.assertEqual(ingredients.count(), 2)
        self.assertIn(ingredient1, ingredients)
        self.assertIn(ingredient2, ingredients)

    def test_partial_update_recipe(self):
        """Test updating a recipe with patch"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        new_tag = sample_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_recipe(self):
        """Test updaing a recipe with put"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))

        payload = {
            'title': 'Spahetti carbonara',
            'time_minutes': 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_minutes, payload['time_minutes'])
        self.assertEqual(recipe.price, payload['price'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 0)
Пример #33
0
class RecipeImageUploadTests(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user('user', 'testpass')
        self.client.force_authenticate(self.user)
        self.recipe = sample_recipe(user=self.user)

    # remover all the test system
    def tearDown(self):
        self.recipe.image.delete()

    def test_upload_image_to_recipe(self):
        """Test upload an image t orecipe"""
        url = image_upload_url(self.recipe.id)
        with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
            img = Image.new('RGB', (10, 10))
            img.save(ntf, format='JPEG')
            # python seek, back to beginning.
            ntf.seek(0)
            # mulipart format ,
            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_request(self):
        """"Test upload an invlaid image"""
        url = image_upload_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):
        """Test returning recipes with specific tags"""
        recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')
        recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')
        tag1 = sample_tag(user=self.user, name='Vegan')
        tag2 = sample_tag(user=self.user, name='Vegetarian')
        recipe1.tags.add(tag1)
        recipe2.tags.add(tag2)
        recipe3 = sample_recipe(user=self.user, title='Fish and chips')

        res = self.client.get(RECIPES_URL,
                              {'tags': '{},{}'.format(tag1.id, tag2.id)})

        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)
        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)

    def test_filter_recipes_by_ingredients(self):
        """Test returning recipes with specific ingredients"""
        recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')
        recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore')
        ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')
        ingredient2 = sample_ingredient(user=self.user, name='Chicken')
        recipe1.ingredients.add(ingredient1)
        recipe2.ingredients.add(ingredient2)
        recipe3 = sample_recipe(user=self.user, title='Steak and mushrooms')

        res = self.client.get(
            RECIPES_URL,
            {'ingredients': '{},{}'.format(ingredient1.id, ingredient2.id)})

        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)
        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)
Пример #34
0
class PrivateIngredientsAPITests(TestCase):
    """Test ingredients API by authorized user"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            email="*****@*****.**", password="******")
        self.client.force_authenticate(user=self.user)

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

        response = self.client.get(INGREDIENTS_URL)

        ingredients = Ingredient.objects.all().order_by('-name')
        serializer = IngredientSerializer(ingredients, many=True)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.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(
            email="*****@*****.**", password="******")
        Ingredient.objects.create(user=user2, name='ven')
        ingredient = Ingredient.objects.create(user=self.user, name='Tum')

        response = self.client.get(INGREDIENTS_URL)

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

    def test_create_ingredient_successful(self):
        """Test creating a new ingredient"""
        payload = {'name': 'Test Ingredient'}

        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 a new ingredient with invalid payload"""
        payload = {'name': ''}

        response = self.client.post(INGREDIENTS_URL, payload)

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

    def test_retrieve_ingredients_assigned_to_recipes(self):
        """Test retrieving only ingredients that are assigned to recipes"""

        ingredient1 = sample_ingredient(user=self.user, name='tomato')
        ingredient2 = sample_ingredient(user=self.user, name='onion')

        recipe = sample_recipe(user=self.user)
        recipe.ingredients.add(ingredient1)

        response = self.client.get(INGREDIENTS_URL, {'assigned_only': 1})
        serializer1 = IngredientSerializer(ingredient1)
        serializer2 = IngredientSerializer(ingredient2)
        self.assertIn(serializer1.data, response.data)
        self.assertNotIn(serializer2.data, response.data)

    def test_retrieve_ingredients_assigned_unique(self):
        """Test filtering ingredients by assigned returns unique items"""
        ingredient = Ingredient.objects.create(user=self.user,
                                               name='Breakfast')
        Ingredient.objects.create(user=self.user, name='Lunch')
        recipe1 = Recipe.objects.create(title='Pancakes',
                                        time_minutes=5,
                                        price=3.00,
                                        user=self.user)
        recipe1.ingredients.add(ingredient)
        recipe2 = Recipe.objects.create(title='Porridge',
                                        time_minutes=3,
                                        price=2.00,
                                        user=self.user)
        recipe2.ingredients.add(ingredient)

        response = self.client.get(INGREDIENTS_URL, {'assigned_only': 1})

        self.assertEqual(len(response.data), 1)
class PrivateTagsApiTest(TestCase):
    # test the authorized user tags API

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            '*****@*****.**',
            'testpassword',
        )

        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')

        response = self.client.get(TAGS_URL)

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

    def test_tags_limited_to_user(self):
        # test that tags returned are for the authenticated user
        # and not for the other user
        user2 = get_user_model().objects.create_user(
            '*****@*****.**',
            'test2password2',
        )

        Tag.objects.create(user=user2, name='Thai')
        tag = Tag.objects.create(user=self.user, name='Chinese')

        response = self.client.get(TAGS_URL)

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

    def test_create_tag_successful(self):
        # test creating a nwe 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 nwe tag with invalid payload
        payload = {'name': ''}

        response = self.client.post(TAGS_URL, payload)

        self.assertEqual(response.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,
                                       user=self.user)
        recipe.tags.add(tag1)

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

        serializer1 = TagSerializer(tag1)
        serializer2 = TagSerializer(tag2)
        self.assertIn(serializer1.data, response.data)
        self.assertNotIn(serializer2.data, response.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')
        Tag.objects.create(user=self.user, name='Lunch')
        recipe1 = Recipe.objects.create(title='Pancakes',
                                        time_minutes=5,
                                        price=3,
                                        user=self.user)
        recipe1.tags.add(tag)

        recipe2 = Recipe.objects.create(title='Porridge',
                                        time_minutes=3,
                                        price=2,
                                        user=self.user)
        recipe2.tags.add(tag)

        response = self.client.get(TAGS_URL, {'assigned_only': 1})
        self.assertEqual(len(response.data), 1)
Пример #36
0
class PrivateTagsApiTests(TestCase):
	"""Test the authorized uesr tags API"""

	def setUp(self):
		self.user = get_user_model().objects.create_user(
        	'*****@*****.**',
        	'pass123'
			)

		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 = 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(
            '*****@*****.**',
            'testpass'
			)
		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']
			)
		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_retrive_tags_assigned_to_recipes(self):
		"""Test filtering tags by those assigned to recipe"""
		tag1 = Tag.objects.create(user=self.user, name='Breakfast')
		tag2 = Tag.objects.create(user=self.user, name='Lunch')
		recipe = Recipe.objects.create(
			title='Corianser 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 = TagSerializer(tag1)
		serializer2 = TagSerializer(tag2)
		self.assertIn(serializer1.data, res.data)
		self.assertNotIn(serializer2.data, res.data)
Пример #37
0
class PrivateRecipeApiTests(TestCase):
    """Test unauthenticated recipe API access"""

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

        self.client.force_authenticate(self.user)

    def test_retrieve_recipes(self):
        """Test retrieving a list of recipes"""
        sample_recipe(user=self.user)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPE_URLS)

        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_limited_to_user(self):
        """Test retrieving recipes for users"""
        user2 = get_user_model().objects.create_user(
            '*****@*****.**',
            'pass234'
        )
        sample_recipe(user=user2)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPE_URLS)

        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_detail(self):
        """Test viewin a recipe detail"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        recipe.ingredient.add(sample_ingredient(user=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"""
        payload = {
            'title': 'Chocolate Cheesecake',
            'time_minutes': 30,
            'price': 5.00
        }
        res = self.client.post(RECIPE_URLS, payload)

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

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

        payload = {
            'title': 'Avocado lime cheesecake',
            'tags': [tag1.id, tag2.id],
            'time_minutes': 60,
            'price': 20.00
        }
        res = self.client.post(RECIPE_URLS, 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_ingredients(self):
        """Test creating recipes with ingredients"""
        ingredient1 = sample_ingredient(user=self.user, name='Prawns')
        ingredient2 = sample_ingredient(user=self.user, name='Ginger')
        payload = {
            'title': 'Thai prawn red curry',
            'ingredient': [ingredient1.id, ingredient2.id],
            'time_minutes': 20,
            'price': 7.00
        }
        res = self.client.post(RECIPE_URLS, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingredients = recipe.ingredient.all()
        self.assertEqual(ingredients.count(), 2)
        self.assertIn(ingredient1, ingredients)
        self.assertIn(ingredient2, ingredients)

    def test_partial_update_recipe(self):
        """Test updating a recipe with PATCH"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        new_tag = sample_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_recipe(self):
        """Test updating a recipe with PUT"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        payload = {
            'title': 'Spaghetti',
            'time_minutes': 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_minutes, payload['time_minutes'])
        self.assertEqual(recipe.price, payload['price'])
        tags = recipe.tags.all()
        self.assertEqual(len(tags), 0)
Пример #38
0
def admin_client(db, admin_user):
    client = APIClient()
    client.force_authenticate(user=admin_user)
    return client
Пример #39
0
class BulkUserRetirementViewTests(APITestCase):
    """
    Tests the bulk user retirement api
    """
    def setUp(self):
        super().setUp()
        login_client = APIClient()
        self.user1 = UserFactory.create(username='******',
                                        email='*****@*****.**',
                                        password='******',
                                        profile__name="Test User1")
        login_client.login(username=self.user1.username,
                           password='******')
        self.user2 = UserFactory.create(username='******',
                                        email='*****@*****.**',
                                        password='******',
                                        profile__name="Test User2")
        login_client.login(username=self.user2.username,
                           password='******')
        self.user3 = UserFactory.create(username='******',
                                        email='*****@*****.**',
                                        password='******',
                                        profile__name="Test User3")
        self.user4 = UserFactory.create(username='******',
                                        email='*****@*****.**',
                                        password='******',
                                        profile__name="Test User4")
        RetirementState.objects.create(state_name='PENDING',
                                       state_execution_order=1,
                                       is_dead_end_state=False,
                                       required=True)
        self.pending_state = RetirementState.objects.get(state_name='PENDING')
        # Use a separate client for retirement worker (don't mix cookie state)
        self.client = APIClient()
        self.client.force_authenticate(user=self.user1)

    def test_gdpr_user_retirement_api(self):
        user_retirement_url = reverse('bulk_retirement_api')
        expected_response = {
            'successful_user_retirements': [self.user2.username],
            'failed_user_retirements': []
        }
        with self.settings(
                RETIREMENT_SERVICE_WORKER_USERNAME=self.user1.username):
            response = self.client.post(user_retirement_url,
                                        {"usernames": self.user2.username})
            assert response.status_code == 200
            assert response.data == expected_response

            retirement_status = UserRetirementStatus.objects.get(
                user__username=self.user2.username)
            assert retirement_status.current_state == self.pending_state

    def test_retirement_for_non_existing_users(self):
        user_retirement_url = reverse('bulk_retirement_api')
        expected_response = {
            'successful_user_retirements': [],
            'failed_user_retirements': ["non_existing_user"]
        }
        with self.settings(
                RETIREMENT_SERVICE_WORKER_USERNAME=self.user1.username):
            response = self.client.post(user_retirement_url,
                                        {"usernames": "non_existing_user"})
            assert response.status_code == 200
            assert response.data == expected_response

    def test_retirement_for_multiple_users(self):
        user_retirement_url = reverse('bulk_retirement_api')
        expected_response = {
            'successful_user_retirements':
            [self.user3.username, self.user4.username],
            'failed_user_retirements': []
        }
        with self.settings(
                RETIREMENT_SERVICE_WORKER_USERNAME=self.user1.username):
            response = self.client.post(
                user_retirement_url,
                {"usernames": f'{self.user3.username},{self.user4.username}'})

            assert response.status_code == 200
            assert sorted(response.data['successful_user_retirements']) == sorted(expected_response['successful_user_retirements'])  # pylint: disable=line-too-long

            retirement_status_1 = UserRetirementStatus.objects.get(
                user__username=self.user3.username)
            assert retirement_status_1.current_state == self.pending_state

            retirement_status_2 = UserRetirementStatus.objects.get(
                user__username=self.user4.username)
            assert retirement_status_2.current_state == self.pending_state

    def test_retirement_for_multiple_users_with_some_nonexisting_users(self):
        user_retirement_url = reverse('bulk_retirement_api')
        expected_response = {
            'successful_user_retirements':
            [self.user3.username, self.user4.username],
            'failed_user_retirements': ['non_existing_user']
        }

        with self.settings(
                RETIREMENT_SERVICE_WORKER_USERNAME=self.user1.username):
            response = self.client.post(
                user_retirement_url, {
                    "usernames":
                    '{user1},{user2}, non_existing_user'.format(
                        user1=self.user3.username, user2=self.user4.username)
                })
            assert response.status_code == 200

            assert sorted(response.data['successful_user_retirements']) == sorted(expected_response['successful_user_retirements'])  # pylint: disable=line-too-long

            retirement_status_1 = UserRetirementStatus.objects.get(
                user__username=self.user3.username)
            assert retirement_status_1.current_state == self.pending_state

            retirement_status_2 = UserRetirementStatus.objects.get(
                user__username=self.user4.username)
            assert retirement_status_2.current_state == self.pending_state

    def test_retirement_for_unauthorized_users(self):
        user_retirement_url = reverse('bulk_retirement_api')
        response = self.client.post(user_retirement_url,
                                    {"usernames": self.user2.username})
        assert response.status_code == 403
Пример #40
0
class PrivateIngredientsAPITests(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            "*****@*****.**", "testpass"
        )
        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):
        user2 = get_user_model().objects.create_user(
            "*****@*****.**", "testpass"
        )
        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_sucessful(self):
        payload = {"name": "Carrot"}
        self.client.post(INGREDIENTS_URL, payload)

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

        self.assertTrue(exists)

    def test_create_invalid_ingredient(self):
        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):
        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_ingredient_assigned_unique(self):
        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="Green 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)
class PrivateIngredientApiTests(TestCase):
    '''Test private ingredients api'''
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'testpass')
        self.client.force_authenticate(self.user)

    def test_retrieve_ingredients_list(self):
        '''retrieving a list of ingredient'''
        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')
        serialzer = IngredientSerializer(ingredients, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serialzer.data)

    def test_ingredients_limited_to_user(self):
        '''test that ingredients for the authenticated user are returned'''
        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'testpass')
        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_successfull(self):
        '''Test create a new ingredient'''
        payload = {'name': 'Cabage'}
        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_ingredient_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.00,
                                       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_assign_unique(self):
        ''' test filtering ingredients by assigned returned 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='corriender eggs omellte',
                                        time_minutes=30,
                                        price=10.00,
                                        user=self.user)
        recipe2.ingredients.add(ingredient)
        res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1})
        self.assertEqual(len(res.data), 1)
Пример #42
0
class ApiTestCase(TestCase):
    """
    Runs tests for the endpoints
    """
    def setUp(self):
        # client for simulating http requests
        self.client = APIClient()

        # test user for authenticaction
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')

        # test data used in the test cases
        with open("api_tests/data.json") as data_file:
            self.test_data = json.load(data_file)

        self.user = user

        # force authentication for all requests
        self.client.force_authenticate(user=user)

    def test_user_can_log_in(self):
        """
        Test the login endpoint
        /login/
        """
        # create a user
        User.objects.create_user(username='******',
                                 email='*****@*****.**',
                                 password='******')

        credentials = {
            "username": "******",
            "password": "******"
        }

        # use credentials of the user created to test the log in
        response = self.client.post('/login/', credentials,
                                    format='json')

        # assert the login was successful
        self.assertEqual(response.status_code,
                         status.HTTP_200_OK)

        data = response.json()

        # assert a token is returned for every successfull login
        assert "token" in data

    def test_if_user_can_retrive_drinks(self):
        """
        Test the retrieve drinks enpoint
        /data/drinks"
        """
        # take data from the ones extracted from the json file 
        drinks = self.test_data["drinks"]
        save_drinks = []
        for drink in drinks:
            drink = Drink(**drink)
            save_drinks.append(drink)
        Drink.objects.bulk_create(save_drinks)

        drink_count = Drink.objects.count()

        # assert the saving of the drinks was successful
        self.assertEqual(drink_count, 10)

        # retrieve the data via a request
        response = self.client.get("/data/drinks/")

        # assert the request was successful
        self.assertEqual(response.status_code,
                         status.HTTP_200_OK)

        recieved_data_count = len(response.json())

        # assert the number of drinks recieved is correct
        self.assertEqual(recieved_data_count, 10)

    def test_if_user_can_add_and_retrieve_data(self):
        """
        Test the add data endpoint
        /data/data_collected/
        """
        # take the first three drinks
        drinks = self.test_data["drinks"][:3]
        # create drink objects from the json data
        drinks = [Drink(**i) for i in drinks]
        Drink.objects.bulk_create(drinks)

        data = self.test_data["data"][0]
        # use drink ids added to the db for this particular
        # test
        data["drink_id"] = drinks[random.randint(0, 2)]._id

        response = self.client.post("/data/data_collected/",
                                    data, format='json')

        # assert it data was added correctly
        self.assertEqual(response.status_code,
                         status.HTTP_201_CREATED)

        # retrieve the data added
        response = self.client.get("/data/data_collected/")

        # assert if the response is 200
        self.assertEqual(response.status_code, 200)

        # get the number of added data records
        data_added_count = len(response.json())

        # assert if the data added is one
        self.assertEqual(data_added_count, 1)

    def test_if_user_can_update_data_added(self):
        """
        Test the retrieve one, update and delete endpoint
        /data/record/<record_id>/
        """
        drink_data = self.test_data["drinks"][0]
        # save a drink
        drink = Drink(**drink_data)
        drink.save()

        record_data = self.test_data["data"][0]
        data = Data(
            favorite_drink=drink,
            consumer_name=record_data["consumer_name"],
            location=record_data["location"],
            collector=self.user,
            location_longitude=record_data["location_longitude"],
            location_latitude=record_data["location_latitude"]
        )
        # save a data record
        data.save()

        # retrieve the added data record
        url = "/data/record/%s/" % data._id
        get_response = self.client.get(url)

        self.assertEqual(get_response.status_code,
                         status.HTTP_200_OK)
        recieved_data = get_response.json()
        self.assertEqual(recieved_data["consumer_name"],
                         "dirk nowitzki")

        # update the data record
        update_payload = {
            "drink_id": str(drink._id),
            "consumer_name": "erick omondi",
            "location": "buruburu",
            "location_longitude": "55.255",
            "location_latitude": "74.2245"
        }

        put_response = self.client.put(url, update_payload, format="json")
        self.assertEqual(put_response.status_code,
                         status.HTTP_200_OK)

        # retrieve the updated record
        updated_data = Data.objects.all()[0]
        # assert it has been updated
        self.assertNotEqual(updated_data.consumer_name,
                            recieved_data["consumer_name"])

        # delete the record
        delete_response = self.client.delete(url)
        # assert the status code is 204 no content
        self.assertEqual(delete_response.status_code,
                         status.HTTP_204_NO_CONTENT)
        # assert the record was actually deleted from the database
        data_count = Data.objects.count()
        self.assertEqual(data_count, 0)
Пример #43
0
class MoviesAPITestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.expected_genre = Genre.objects.create(name='Test Movie Genre')
        self.test_movie_data = {
            'title': 'Hydrogen',
            'release_date': '2006-01-01',
            'genres': ['/api/genres/{}/'.format(self.expected_genre.id)]
        }

    # create
    def test_movie_logged_create(self):
        self.client.force_authenticate(user=self.user)
        response = self.client.post('/api/movies/',
                                    self.test_movie_data,
                                    format='json')
        self.client.force_authenticate(user=None)
        data = response.data
        self.assertEqual(response.status_code, 201)
        self.assertEqual(data.get('title'), self.test_movie_data['title'])
        self.assertEqual(data.get('release_date'),
                         self.test_movie_data['release_date'])
        self.assertTrue('/genres/{}'.format(self.expected_genre.id) in
                        ','.join(data.get('genres')))

    def test_movie_anon_create(self):
        response = self.client.post('/api/movies/',
                                    self.test_movie_data,
                                    format='json')
        self.assertEqual(response.status_code, 403)

    # read
    def test_movie_logged_read(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        self.client.force_authenticate(user=self.user)
        response = self.client.get('/api/movies/{}/'.format(test_movie.id),
                                   format='json')
        self.client.force_authenticate(user=None)
        data = response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('title'), self.test_movie_data['title'])
        self.assertEqual(data.get('release_date'),
                         self.test_movie_data['release_date'])

    def test_movie_anon_read(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        self.client.force_authenticate(user=self.user)
        response = self.client.get('/api/movies/{}/'.format(test_movie.id),
                                   format='json')
        data = response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('title'), self.test_movie_data['title'])
        self.assertEqual(data.get('release_date'),
                         self.test_movie_data['release_date'])

    # update
    def test_movie_logged_update(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        expected_movie_data = {
            'title': 'Updated Title',
            'release_date': '1970-01-01',
            'genres': ['/api/genres/{}/'.format(self.expected_genre.id)]
        }
        self.client.force_authenticate(user=self.user)
        response = self.client.put('/api/movies/{}/'.format(test_movie.id),
                                   expected_movie_data,
                                   format='json')
        self.client.force_authenticate(user=None)
        data = response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('title'), expected_movie_data['title'])
        self.assertEqual(data.get('release_date'),
                         expected_movie_data['release_date'])

    def test_movie_anon_update(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        expected_movie_data = {
            'title': 'Updated Title',
            'release_date': '1970-01-01',
            'genres': ['/api/genres/{}/'.format(self.expected_genre.id)]
        }
        response = self.client.put('/api/movies/{}/'.format(test_movie.id),
                                   expected_movie_data,
                                   format='json')
        self.assertEqual(response.status_code, 403)

    # delete
    def test_movie_logged_delete(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        self.client.force_authenticate(user=self.user)
        response = self.client.delete('/api/movies/{}/'.format(test_movie.id),
                                      format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 204)

    def test_movie_anon_delete(self):
        test_movie = Movie.objects.create(
            title=self.test_movie_data['title'],
            release_date=self.test_movie_data['release_date'])
        test_movie.genres.add(self.expected_genre.id)
        test_movie.save()
        response = self.client.delete('/api/movies/{}/'.format(test_movie.id),
                                      format='json')
        self.assertEqual(response.status_code, 403)

    # list
    def test_movie_logged_list(self):
        test_movies = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        for movie in test_movies:
            m = Movie.objects.create(
                title=movie, release_date=self.test_movie_data['release_date'])
            m.genres.add(self.expected_genre)
            m.save()
        self.client.force_authenticate(user=self.user)
        response = self.client.get('/api/movies/', format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('count'), len(test_movies))

    def test_movie_anon_list(self):
        test_movies = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        for movie in test_movies:
            m = Movie.objects.create(
                title=movie, release_date=self.test_movie_data['release_date'])
            m.genres.add(self.expected_genre)
            m.save()
        response = self.client.get('/api/movies/', format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('count'), len(test_movies))

    # filter by genre
    def test_movie_genre_filter(self):
        test_movies = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        another_genre = Genre.objects.create(name='Another Genre')
        for idx, movie in enumerate(test_movies):
            m = Movie.objects.create(
                title=movie, release_date=self.test_movie_data['release_date'])
            if idx % 2 > 0:
                m.genres.add(self.expected_genre)
            else:
                m.genres.add(another_genre)
            m.save()
        # single filter
        response = self.client.get('/api/movies/?genres={}'.format(
            another_genre.id),
                                   format='json')
        data = response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('count'), 3)
        # multiple filter
        response = self.client.get('/api/movies/?genres={}&genres={}'.format(
            self.expected_genre.id, another_genre.id),
                                   format='json')
        data = response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('count'), 6)

    # sequels count
    def test_movie_sequels_count(self):
        test_movies = [
            'The Godfather', 'The Godfather Part II', 'The Godfather Part III'
        ]
        movies = []
        for movie in test_movies:
            m = Movie.objects.create(
                title=movie, release_date=self.test_movie_data['release_date'])
            m.genres.add(self.expected_genre)
            m.save()
            movies.append(m)
        # sequels
        response = self.client.get('/api/movies/{}/'.format(movies[0].id),
                                   format='json')
        data = response.data
        self.assertEqual(data.get('sequels_count'), 2)
        response = self.client.get('/api/movies/{}/'.format(movies[1].id),
                                   format='json')
        data = response.data
        self.assertEqual(data.get('sequels_count'), 1)
        # no sequels
        response = self.client.get('/api/movies/{}/'.format(movies[2].id),
                                   format='json')
        data = response.data
        self.assertEqual(data.get('sequels_count'), 0)
Пример #44
0
class ClanViewsTestCase(TestCase):
    def setUp(self):
        self.game = Game.objects.create(game='Test', slug='test')
        self.user = User.objects.create(username='******',
                                        password='******',
                                        game=self.game)

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

    def test_clan_list(self):
        """TEST VIEW ClanListView OK (GET): Get list of all clans"""
        n = 5
        users = [
            User.objects.create(username=f'Test{index}',
                                password='******',
                                game=self.game) for index in range(n)
        ]
        clans = [
            GameClan.create(creator=user,
                            name=f'{user.username} Clan',
                            description='TEST',
                            game=self.game) for user in users
        ]

        url = reverse('clans')
        response = self.client.get(url)
        self.assertEqual(n, len(response.data))

    def test_creating_clan__creating_clan_member__creating_clan_chat(self):
        """TEST VIEW ClanListView OK (GET): Creating ClanMember and ClanChat while creating clan"""
        url = reverse('clan-create')
        data = {"name": "Test", "description": "TestClan"}

        response = self.client.post(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.user.my_clan.name, 'Test')
        self.assertEqual(self.user.my_clan.chat.name, 'Test')
        self.assertEqual(self.user.my_clan.creator, self.user)
        self.assertTrue(self.user.clan_member)

    def test_creating_clan__invalid_name(self):
        """TEST VIEW ClanListView BAD REQUEST (GET): Create clan if name not UNIQUE"""
        clan_name = 'CLAN'
        new_user = User.objects.create(username=f'Test1',
                                       password='******',
                                       game=self.game)
        clan = GameClan.create(creator=new_user,
                               name=f'{clan_name}',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-create')
        data = {"name": clan_name, "description": "TestClan"}

        response = self.client.post(url, data, format='json')

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

    def test_creating_clan__invalid_creator(self):
        """TEST VIEW ClanListView BAD REQUEST (GET): Create clan, But creator must be UNIQUE and have a game"""
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-create')
        data = {"name": 'Test1', "description": "TestClan"}

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        new_client = APIClient()
        new_client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_clan_detail_view(self):
        """TEST VIEW ClanView OK (GET): Get GameClan"""
        new_user = User.objects.create(username=f'Test1',
                                       password='******',
                                       game=self.game)
        clan = GameClan.create(creator=new_user,
                               name='TEST1',
                               description='TEST',
                               game=self.game)
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)
        url = reverse('clan')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response = self.client.get(url + '?id=2', )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_clan_detail_view__clan_not_exist(self):
        """TEST VIEW ClanView BAD REQUEST (GET): Get GameClan, But Clan not exist"""
        url = reverse('clan')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        response = self.client.get(url + '?id=2')
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_clan_update(self):
        """TEST VIEW UpdateClanView OK (POST): Update GameClan"""
        clan = GameClan.create(creator=self.user,
                               name='TEST1',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-update')
        data = {'name': 'Test1', 'description': 'TEST!', 'max_members': 2}
        response = self.client.post(url, data)
        clan.refresh_from_db()

        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual(data['name'], clan.name)
        self.assertEqual(data['description'], clan.description)
        self.assertEqual(data['max_members'], clan.max_members)

    def test_clan_update__invalid_clan_id(self):
        """TEST VIEW UpdateClanView BAD REQUEST (POST): Update GameClan, But Clan do not exist"""
        url = reverse('clan-update')
        data = {'name': 'Test1', 'description': 'TEST!', 'max_members': 2}
        response = self.client.post(url, data)
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)

    def test_clan_update__invalid_user(self):
        """TEST VIEW UpdateClanView BAD REQUEST (POST): Update GameClan, But not from creator"""
        new_user = User.objects.create(username=f'Test1',
                                       password='******',
                                       game=self.game)
        clan = GameClan.create(creator=new_user,
                               name='TEST1',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-update')
        data = {'name': 'Test1', 'description': 'TEST!', 'max_members': 2}
        response = self.client.post(url, data)
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)

    def test_clan_update__invalid_unique_name(self):
        """TEST VIEW UpdateClanView BAD REQUEST (POST): Update GameClan, But clan with such name already exist"""
        new_user = User.objects.create(username=f'Test1',
                                       password='******',
                                       game=self.game)
        clan2 = GameClan.create(creator=new_user,
                                name='TEST1',
                                description='TEST',
                                game=self.game)
        clan1 = GameClan.create(creator=self.user,
                                name='TEST2',
                                description='TEST',
                                game=self.game)

        url = reverse('clan-update')
        data = {'name': 'TEST1', 'description': 'TEST!', 'max_members': 2}
        response = self.client.post(url, data)
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)

    def test_clan_delete(self):
        """TEST VIEW DeleteClanView OK (POST): Delete GameClan"""
        new_user = User.objects.create(username=f'Test1',
                                       password='******',
                                       game=self.game)
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-delete')
        data = {}
        response = self.client.post(url, data)
        self.assertEqual(status.HTTP_200_OK, response.status_code)

    def test_clan_remove_member(self):
        """TEST VIEW RemoveClanMember OK (POST): Remove User from the GameClan"""
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)
        new_user = User.objects.create(username='******',
                                       password='******',
                                       game=self.game)
        clan.add(new_user)

        url = reverse('clan-remove-member')
        param = f'?member_id={new_user.id}'
        response = self.client.post(url + param)
        self.assertEqual(status.HTTP_200_OK, response.status_code)

    def test_clan_remove_invalid__user_not_exists(self):
        """TEST VIEW RemoveClanMemberView BAD REQUEST (POST): Removing User from the GameClan,
            But User not exists"""
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-remove-member')
        param = f'?member_id=10'
        response = self.client.post(url + param)
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)

    def test_clan_remove_invalid__user_not_in_user_clan(self):
        """TEST VIEW RemoveClanMemberView BAD REQUEST (POST): Removing User from the GameClan,
            But User in another GameClan"""
        clan = GameClan.create(creator=self.user,
                               name='TEST',
                               description='TEST',
                               game=self.game)
        new_user = User.objects.create(username='******',
                                       password='******',
                                       game=self.game)
        clan = GameClan.create(creator=new_user,
                               name='TEST1',
                               description='TEST',
                               game=self.game)

        url = reverse('clan-remove-member')
        param = f'?member_id={new_user.id}'
        response = self.client.post(url + param)
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
Пример #45
0
class OrganizationTestCase(APITestCase):
    def setUp(self):
        self.client = APIClient()

        # Create each type of user that could be making the registration request
        self.system_admin = CustomUser.objects.create(
            user_name='system_admin1',
            email='*****@*****.**',
            password='******',
            first_name='system1',
            last_name='admin1',
            role='SA',
            is_active=True)

        self.inventory_manager = CustomUser.objects.create(
            user_name='inventory_manager1',
            email='*****@*****.**',
            password='******',
            first_name='inventory1',
            last_name='manage1r',
            role='IM',
            is_active=True)

    @factory.django.mute_signals(signals.pre_save, signals.post_save)
    def test_create_organization_sys_admin_success(self):
        """ Organization was created correctly """
        self.client.force_authenticate(user=self.system_admin)
        data = {'org_name': 'test_case'}
        response = self.client.post("/organization/", data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_organization_inventory_manager_success(self):
        """ Inventory manager is not allowed to create an organization """
        self.client.force_authenticate(user=self.inventory_manager)
        data = {'org_name': 'test_case'}
        response = self.client.post("/organization/", data)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_create_organization_failure(self):
        """ User can't create organization if missing fields """
        self.client.force_authenticate(user=self.system_admin)
        data = {}
        response = self.client.post("/organization/", data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_organization_unauthorized_request(self):
        """ User can't access any of the method if token is not in header of request """
        response = self.client.get("/organization/")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_organization_unauthorized_clearence(self):
        """ IM can create or delete an organization """
        self.client.force_authenticate(user=self.inventory_manager)
        response = self.client.delete("/organization/")
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_get_all_organization(self):
        """ IM can get a list of organization """
        self.client.force_authenticate(user=self.inventory_manager)
        response = self.client.get("/organization/")
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Пример #46
0
class GenreAPITestCase(APITransactionTestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')

    # create
    def test_genre_logged_create(self):
        expected_name = 'Test Genre'
        self.client.force_authenticate(user=self.user)
        response = self.client.post('/api/genres/', {'name': expected_name},
                                    format='json')
        self.client.force_authenticate(user=None)
        test_genre = Genre.objects.get(name=expected_name)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(test_genre.name, expected_name)

    def test_genre_anon_create(self):
        expected_name = 'Test Genre'
        response = self.client.post('/api/genres/', {'name': expected_name},
                                    format='json')
        self.assertEqual(response.status_code, 403)

    # read
    def test_genre_logged_read(self):
        expected_name = 'Test Genre'
        test_genre = Genre.objects.create(name=expected_name)
        self.client.force_authenticate(user=self.user)
        response = self.client.get('/api/genres/{}/'.format(test_genre.id),
                                   format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('name'), expected_name)

    def test_genre_anon_read(self):
        expected_name = 'Test Genre'
        test_genre = Genre.objects.create(name=expected_name)
        response = self.client.get('/api/genres/{}/'.format(test_genre.id),
                                   format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('name'), expected_name)

    # update
    def test_genre_logged_update(self):
        initial_name = 'Test Genre'
        expected_name = 'Updated Genre'
        test_genre = Genre.objects.create(name=initial_name)
        self.client.force_authenticate(user=self.user)
        response = self.client.put('/api/genres/{}/'.format(test_genre.id),
                                   {'name': expected_name},
                                   format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('name'), expected_name)

    def test_genre_anon_update(self):
        initial_name = 'Test Genre'
        expected_name = 'Updated Genre'
        test_genre = Genre.objects.create(name=initial_name)
        response = self.client.put('/api/genres/{}/'.format(test_genre.id),
                                   {'name': expected_name},
                                   format='json')
        self.assertEqual(response.status_code, 403)

    # delete
    def test_genre_logged_delete(self):
        test_genre = Genre.objects.create(name='Test Genre')
        self.client.force_authenticate(user=self.user)
        response = self.client.delete('/api/genres/{}/'.format(test_genre.id),
                                      format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 204)

    def test_genre_anon_delete(self):
        test_genre = Genre.objects.create(name='Test Genre')
        response = self.client.delete('/api/genres/{}/'.format(test_genre.id),
                                      format='json')
        self.assertEqual(response.status_code, 403)

    # list
    def test_genre_logged_list(self):
        test_genres = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        for genre_name in test_genres:
            Genre.objects.create(name=genre_name)
        self.client.force_authenticate(user=self.user)
        response = self.client.get('/api/genres/', format='json')
        self.client.force_authenticate(user=None)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('count'), len(test_genres))

    def test_genre_anon_list(self):
        test_genres = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        for genre_name in test_genres:
            Genre.objects.create(name=genre_name)
        response = self.client.get('/api/genres/', format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('count'), len(test_genres))

    # movie counts
    def test_genre_movie_count(self):
        test_genre = Genre.objects.create(name='Test Genre')
        another_genre = Genre.objects.create(name='Another Genre')
        test_movies = ['Helium', 'Neon', 'Argon', 'Krypton', 'Xenon', 'Radon']
        for idx, movie in enumerate(test_movies):
            test_movie_data = {'title': movie, 'release_date': '2006-01-01'}
            m = Movie.objects.create(**test_movie_data)
            if idx % 2 > 0:
                m.genres.add(test_genre)
            else:
                m.genres.add(another_genre)
            m.save()

        response = self.client.get('/api/genres/{}/'.format(test_genre.id),
                                   format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data.get('movie_count'), 3)
Пример #47
0
 def test_delete_other_family(self):
     client = APIClient(HTTP_X_REAL_IP='127.0.0.1')
     client.force_authenticate(user=self.user)
     url = '/api/relation/{0}/'.format(self.relation3.id)
     response = client.delete(url, format='json')
     self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class PrivateIngredientsApiTests(TestCase):
    """test ing can be retr by auth user"""

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

    def test_retrieve_ingredient_list(self):
        """Test retr a list of ingr"""
        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 ingr for the auth user are ret"""
        user2 = get_user_model().objects.create_user(
            '*****@*****.**',
            'test2pass'
        )
        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': 'Cabbbage'}
        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):
        """createing 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 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 teturns unique items"""
        ingredient = Ingredient.objects.create(user=self.user, name='Eggs')
        Ingredient.objects.create(user=self.user, name='Chees')
        recipe1 = Recipe.objects.create(
            title='Eggs benedict',
            time_minutes=31,
            price=12.00,
            user=self.user
        )
        recipe1.ingredients.add(ingredient)
        recipe2 = Recipe.objects.create(
            title='Coriander eggs on toast',
            time_minutes=21,
            price=4.00,
            user=self.user
        )
        recipe2.ingredients.add(ingredient)

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

        self.assertEqual(len(res.data), 1)
class PrivateMasterRunApiTests(TestCase):
    """Test the master run API"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'pass123')
        self.client.force_authenticate(self.user)

    def test_retrieve_master_run_list(self):
        """Test retrieving master run list"""
        MasterRun.objects.create(user=self.user,
                                 date=make_aware(datetime.datetime.now()),
                                 am=True,
                                 vehicle=sample_vehicle(user=self.user))
        MasterRun.objects.create(user=self.user,
                                 date=make_aware(datetime.datetime.now()),
                                 am=True,
                                 vehicle=sample_vehicle(user=self.user))

        res = self.client.get(MASTER_RUN_API)
        master_runs = MasterRun.objects.all()
        serializer = MasterRunSerializer(master_runs, many=True)

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

    def test_create_master_run(self):
        """Test creating a master run"""
        payload = {
            'user': self.user,
            'date': make_aware(datetime.datetime.now()),
            'am': True,
            'vehicle': sample_vehicle(user=self.user).id
        }

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

        exists = MasterRun.objects.filter(user=self.user,
                                          date=payload['date'],
                                          am=payload['am'],
                                          vehicle=payload['vehicle']).exists()

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

    def test_partial_update_master_run(self):
        """Test updating a master run with patch"""
        master_run = sample_master_run(user=self.user,
                                       vehicle=sample_vehicle(user=self.user))

        payload = {'am': False, 'pm': True}

        url = detail_url(master_run.id)
        res = self.client.patch(url, payload)
        master_run.refresh_from_db()

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(master_run.am, payload['am'])
        self.assertEqual(master_run.pm, payload['pm'])

    def test_full_update_master_run(self):
        """Test updating master run with put"""
        master_run = sample_master_run(user=self.user,
                                       vehicle=sample_vehicle(user=self.user))

        new_vehicle = sample_vehicle(user=self.user)
        payload = {
            'date': make_aware(datetime.datetime.now()),
            'vehicle': new_vehicle.id,
            'am': False,
            'pm': True
        }

        url = detail_url(master_run.id)
        res = self.client.put(url, payload)
        master_run.refresh_from_db()

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(master_run.am, payload['am'])
        self.assertEqual(master_run.pm, payload['pm'])
        self.assertEqual(master_run.vehicle, new_vehicle)

    def test_delete_master_run(self):
        """Test deleting a master run"""
        master_run = sample_master_run(user=self.user,
                                       vehicle=sample_vehicle(user=self.user))

        url = detail_url(master_run.id)
        res = self.client.delete(url)

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

    def test_create_master_run_with_drivers(self):
        """Test creating master run with drivers"""
        driver1 = sample_user('*****@*****.**', 'pass222')
        driver2 = sample_user('*****@*****.**', 'pass222')

        payload = {
            'user': self.user,
            'date': make_aware(datetime.datetime.now()),
            'am': True,
            'vehicle': sample_vehicle(user=self.user).id,
            'drivers': [driver1.id, driver2.id]
        }

        res = self.client.post(MASTER_RUN_API, payload)
        url = detail_url(res.data['id'])
        master_run = self.client.get(url)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        self.assertEqual(len(master_run.data['drivers']), 2)
        self.assertIn(driver1.id, master_run.data['drivers'])
        self.assertIn(driver2.id, master_run.data['drivers'])

    def test_create_master_run_with_runs(self):
        """Test creating master runs with runs"""

        run1 = sample_run(
            user=self.user,
            deposit_location=sample_address(user=self.user),
            pick_up_location=sample_address(user=self.user,
                                            address1='Mamie michon'),
            master_run=sample_master_run(
                user=self.user, vehicle=sample_vehicle(user=self.user)),
            patient=sample_patient(user=self.user,
                                   address=sample_address(user=self.user)))

        run2 = sample_run(
            user=self.user,
            deposit_location=sample_address(user=self.user),
            pick_up_location=sample_address(user=self.user,
                                            address1='Mamie Fleury'),
            master_run=sample_master_run(
                user=self.user, vehicle=sample_vehicle(user=self.user)),
            patient=sample_patient(user=self.user,
                                   address=sample_address(user=self.user)))

        payload = {
            'user': self.user,
            'date': make_aware(datetime.datetime.now()),
            'am': True,
            'vehicle': sample_vehicle(user=self.user).id,
            'runs': [run1.id, run2.id]
        }

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

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        master_run = MasterRun.objects.get(id=res.data['id'])
        runs = master_run.runs.all()
        self.assertEqual(len(runs), 2)
        self.assertIn(run1, runs)
        self.assertIn(run2, runs)
class PrivateIngredientsAPITests(TestCase):
    """Test the private ingredients API."""
    def setUp(self) -> None:
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'testpassword123')
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)

    def test_login_required(self):
        self.client.force_authenticate(user=None, token=None)

        response = self.client.get(INGREDIENTS_URL)

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

    def test_retrieve_ingredients_list(self):
        """Test retrieving a list of ingredients."""
        Ingredient.objects.create(user=self.user, name='Mango')
        Ingredient.objects.create(user=self.user, name='Banana')

        # valid data for comparison
        ingredients = Ingredient.objects.all().order_by('-name')
        serializer = IngredientSerializer(ingredients, many=True)
        # api response
        response = self.client.get(INGREDIENTS_URL)

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

    def test_ingredients_limited_to_user(self):
        """Test that ingredients only for the authenticated user are returned."""
        another_user = get_user_model().objects.create_user(
            email='*****@*****.**', password='******')
        # ingredient assigned to another user that we won't be abl to see
        Ingredient.objects.create(user=another_user, name='Papaya')
        # The only visible ingredient
        lime = Ingredient.objects.create(user=self.user, name='Lime')
        # api response
        response = self.client.get(INGREDIENTS_URL)

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

    def test_create_ingredient_successful(self):
        """Test creating a new ingredient."""
        payload = {'name': 'Pineapple'}
        response = self.client.post(INGREDIENTS_URL, payload)

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

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

    def test_create_ingredient_invalid(self):
        """Test create an invalid ingredient fails."""
        payload = {'name': ''}
        response = self.client.post(INGREDIENTS_URL, payload)

        self.assertTrue(response.status_code, status.HTTP_400_BAD_REQUEST)
Пример #51
0
class PrivateRecipeApiTest(TestCase):
    """Test unauthenticated recipe API access"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'testpass')
        self.client.force_authenticate(self.user)

    def test_retrieve_recipes(self):
        """Test retrivieng a list of recipes"""
        sample_recipe(user=self.user)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPES_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_limited_to_user(self):
        """Test retrieving recipes for user"""
        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'pass123')
        sample_recipe(user=user2)
        sample_recipe(user=self.user)

        res = self.client.get(RECIPES_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_detail(self):
        """Test viewing a recipe detail"""
        recipe = sample_recipe(user=self.user)
        recipe.tags.add(sample_tag(user=self.user))
        recipe.ingredients.add(sample_ingredient(user=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"""
        payload = {
            'title': 'Chocolate cheesecake',
            'time_minutes': 30,
            'price': 5.00
        }

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

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

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

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

        res = self.client.post(RECIPES_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_ingredients(self):
        """Test creating recipe with ingredients"""
        ingredient1 = sample_ingredient(user=self.user, name='Tomato')
        ingredient2 = sample_ingredient(user=self.user, name='Ginger')

        payload = {
            'title': 'Thay curry',
            'ingredients': [ingredient1.id, ingredient2.id],
            'time_minutes': 20,
            'price': 7.00
        }
        res = self.client.post(RECIPES_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingredients = recipe.ingredients.all()
        self.assertEqual(ingredients.count(), 2)
        self.assertIn(ingredient1, ingredients)
        self.assertIn(ingredient2, ingredients)
Пример #52
0
class TestViews(APITestCase):
    def setUp(self):
        self.client = APIClient()
        """Define url"""
        self.login_url = reverse('login')
        self.leaderboard_url = reverse('leaderboard')
        self.students_url = reverse('students')
        self.questions_url = reverse('questions')
        self.questions_submit_url = reverse('questions_submit')
        self.create_questions_url = reverse('create-questions')
        self.game_summary_url = reverse('gameSummary')
        """create a user"""
        self.credentials = {
            'email': '*****@*****.**',
            'password': '******',
            'name': 'testuser',
        }
        self.user = User.objects.create_user(**self.credentials)
        """create World"""
        world1 = World.objects.create(name="1")
        world2 = World.objects.create(name="2")
        """create section"""
        section1 = Section.objects.create(name="1")
        section2 = Section.objects.create(name="2")
        """create questions"""
        question1 = Questions_teacher.objects.create(questionBody="1+1 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answers for the question"""
        Questions_answer.objects.create(questionID=question1,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="2",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question1,
                                        questionText="4",
                                        isCorrect=False)

        self.question = question1
        """create questions"""
        question2 = Questions_teacher.objects.create(questionBody="2+2 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answers for the question"""
        Questions_answer.objects.create(questionID=question2,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question2,
                                        questionText="4",
                                        isCorrect=True)
        """create question History for the questions"""
        questionHistory.objects.create(worldID=question2.worldID,
                                       sectionID=question2.sectionID,
                                       questionID=question2,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='4')
        """ create a question """
        question3 = Questions_teacher.objects.create(questionBody="1*1 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question3,
                                        questionText="1",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question3,
                                        questionText="4",
                                        isCorrect=False)
        """ create question History for question"""
        questionHistory.objects.create(worldID=question3.worldID,
                                       sectionID=question3.sectionID,
                                       questionID=question3,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='4')
        """ create a question """
        question4 = Questions_teacher.objects.create(questionBody="2*2 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question4,
                                        questionText="1",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="2",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="3",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question4,
                                        questionText="4",
                                        isCorrect=True)
        """ create question history for the question """
        questionHistory.objects.create(worldID=question4.worldID,
                                       sectionID=question4.sectionID,
                                       questionID=question4,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='4')
        """ create question """
        question5 = Questions_teacher.objects.create(questionBody="10+10 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question5,
                                        questionText="10",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="20",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="30",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question5,
                                        questionText="40",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question5.worldID,
                                       sectionID=question5.sectionID,
                                       questionID=question5,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='40')
        """ create question """
        question6 = Questions_teacher.objects.create(questionBody="10+20 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question6,
                                        questionText="10",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="20",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="30",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question6,
                                        questionText="40",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question6.worldID,
                                       sectionID=question6.sectionID,
                                       questionID=question6,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='30')
        """ create question """
        question7 = Questions_teacher.objects.create(questionBody="10*10 = ?",
                                                     worldID=world1,
                                                     sectionID=section2,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question7,
                                        questionText="100",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="200",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="300",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question7,
                                        questionText="400",
                                        isCorrect=False)
        """ create question history for question"""
        questionHistory.objects.create(worldID=question7.worldID,
                                       sectionID=question7.sectionID,
                                       questionID=question7,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='100')
        """ create question """
        question8 = Questions_teacher.objects.create(questionBody="20*10 = ?",
                                                     worldID=world1,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=2)
        """ create question answer for question"""
        Questions_answer.objects.create(questionID=question8,
                                        questionText="100",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="200",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="300",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question8,
                                        questionText="400",
                                        isCorrect=False)
        """ create question histroy for question"""
        questionHistory.objects.create(worldID=question8.worldID,
                                       sectionID=question8.sectionID,
                                       questionID=question8,
                                       studentID=self.user,
                                       isAnsweredCorrect=True,
                                       studentAnswer='200')
        """ create question """
        question9 = Questions_teacher.objects.create(questionBody=" x + y = ?",
                                                     worldID=world2,
                                                     sectionID=section1,
                                                     role="frontend",
                                                     questionLevel=1)
        """ create question answer for question """
        Questions_answer.objects.create(questionID=question9,
                                        questionText="x",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="x+y",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="y",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question9,
                                        questionText="y",
                                        isCorrect=False)
        """ create question history for question """
        questionHistory.objects.create(worldID=question9.worldID,
                                       sectionID=question9.sectionID,
                                       questionID=question9,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='x')
        """ create question"""
        question10 = Questions_teacher.objects.create(questionBody="y+x = ?",
                                                      worldID=world2,
                                                      sectionID=section1,
                                                      role="frontend",
                                                      questionLevel=2)
        """ create question answer """

        Questions_answer.objects.create(questionID=question10,
                                        questionText="x",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="x+y",
                                        isCorrect=True)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="y",
                                        isCorrect=False)
        Questions_answer.objects.create(questionID=question10,
                                        questionText="x",
                                        isCorrect=False)
        """ create question history for question """
        questionHistory.objects.create(worldID=question10.worldID,
                                       sectionID=question10.sectionID,
                                       questionID=question10,
                                       studentID=self.user,
                                       isAnsweredCorrect=False,
                                       studentAnswer='x')

    def test_user_login_with_no_data(self):
        """test user login with no input is not successful """
        res = self.client.post(self.login_url)
        self.assertEqual(res.status_code, 401)

    def test_user_login_with_correct_data(self):
        """ test user login with correct username/password is succsessful"""
        res = self.client.post(self.login_url, self.credentials, format='json')
        token, created = Token.objects.get_or_create(user=self.user)
        res_data = json.loads(res.content)
        self.assertEqual(
            res_data,
            {
                'user': StudentAccountSerializer(self.user).data,
                'token': token.key
            },
        )
        self.assertEqual(res.status_code, 200)

    def test_user_login_with_wrong_data(self):
        """ test user login with incorect username/password is not successful"""
        res = self.client.post(self.login_url, {
            'email': '*****@*****.**',
            'password': '******'
        },
                               format='json')
        self.assertEqual(res.status_code, 401)

    def test_get_student_withoutQuery(self):
        """ test get student list is successful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.students_url)
        res_data = json.loads(res.content)

        students = User.objects.filter(is_staff=False)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data,
                         StudentAccountSerializer(students, many=True).data)

    def test_get_student_withQuery(self):
        """ test get student data with id is successful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.students_url, {'id': self.user.id},
                              content_type='application/json')
        res_data = json.loads(res.content)

        student = User.objects.get(id=self.user.id)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data, StudentAccountSerializer(student).data)

    def test_get_leaderboard(self):
        """ test get student data to display leader is successful """
        self.client.force_authenticate(user=self.user)
        res = self.client.get(self.leaderboard_url)
        res_data = json.loads(res.content)
        user = User.objects.filter(is_staff=False)
        self.assertEqual(res_data, LeaderBoardSerializer(user, many=True).data)
        self.assertEqual(res.status_code, 200)

    def test_post_question_list_withoutQuery(self):
        """ test get question without data is unsccessful """
        self.client.force_authenticate(user=self.user)
        #res = self.client.get(self.questions_url)
        res = self.client.post(self.questions_url)
        res_data = json.loads(res.content)
        self.assertEqual(res.status_code, 400)

    def test_post_question_list_withQuery(self):
        """ test get question with corect data input is successful """
        self.client.force_authenticate(user=self.user)
        data = {"world": "1", "section": "1", "role": "2", "questionLevel": 1}
        #res = self.client.generic(method="GET", path=self.questions_url, data=json.dumps(
        #    data), content_type='application/json')
        res = self.client.post(self.questions_url, data=data, format='json')
        res_data = json.loads(res.content)

        world = World.objects.get(name='1')
        section = Section.objects.get(name='1')
        questions = Questions_teacher.objects.filter(
            worldID=world, sectionID=section, role='frontend',
            questionLevel=1).order_by('?')[:5]

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res_data,
                         QuestionTeacherSerializer(questions, many=True).data)

    # Post Question Answer
    def test_post_questionAns(self):
        """ test post question answer with data is successful """
        self.client.force_authenticate(user=self.user)
        data = {
            'world': self.question.worldID.name,
            'section': self.question.sectionID.name,
            'questionID': self.question.id,
            'studentID': self.user.id,
            'studentAnswer': '2',
            'isAnsweredCorrect': True,
            'pointGain': 1
        }
        res = self.client.post(self.questions_submit_url,
                               data=data,
                               format='json')
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'pass': True})
        self.assertEqual(res.status_code, 201)

    def test_post_questionAns_Without_Data(self):
        """ test post question answer without data is unsuccessful"""
        self.client.force_authenticate(user=self.user)
        res = self.client.post(self.questions_submit_url)
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'pass': False})
        self.assertEqual(res.status_code, 400)

    # Student Post new Question
    def test_post_create_StudentQuestion_Without_Data(self):
        """ test post create new question by student without data is unsucessful """
        self.client.force_authenticate(user=self.user)
        res = self.client.post(self.create_questions_url)
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'submitted': False})
        self.assertEqual(res.status_code, 400)

    def test_post_create_StudentQuestion_With_Data(self):
        """ test post create new question by student with correct data is successful """
        self.client.force_authenticate(user=self.user)
        data = {
            'Proposer':
            '*****@*****.**',
            'questionBody':
            '10*10 = ?',
            'questionAns': [{
                'questionText': '1',
                'isCorrect': False
            }, {
                'questionText': '10',
                'isCorrect': False
            }, {
                'questionText': '10',
                'isCorrect': False
            }, {
                'questionText': '100',
                'isCorrect': True
            }]
        }
        res = self.client.post(self.create_questions_url,
                               data=data,
                               format='json')
        res_data = json.loads(res.content)

        self.assertEqual(res_data, {'submitted': True})
        self.assertEqual(res.status_code, 201)

    def test_get_game_summary(self):
        """ test get game summary based on correct username is successful """
        self.client.force_authenticate(user=self.user)
        data = {'email': self.user.email}
        res = self.client.generic(method="GET",
                                  path=self.game_summary_url,
                                  data=json.dumps(data),
                                  content_type='application/json')
        res_data = json.loads(res.content)
        student = User.objects.get(email=self.user.email)
        self.assertEqual(res_data, gameSummarySerializer(student).data)
        self.assertEqual(res.status_code, 200)

    def test_game_summary_with_no_input(self):
        """ test get game summary based on no input is successful """
        self.client.force_authenticate(user=self.user)
        res = self.client.generic(method="GET",
                                  path=self.game_summary_url,
                                  content_type='application/json')
        res_data = json.loads(res.content)
        self.assertEqual(res_data, {'Error Message': 'record not found'})
        self.assertEqual(res.status_code, 400)
Пример #53
0
class PrivateIngredientsAPITests(TestCase):
    """Test the private ingredient API"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(
            '*****@*****.**', 'testpass')
        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 only ingredients for authenticated user are returned"""
        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'testpass')
        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 creating 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.00,
                                       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)
Пример #54
0
def _get_client(admin_user):
    client = APIClient()
    client.force_authenticate(user=admin_user)
    return client
Пример #55
0
def api_client(user_factory):
    client = APIClient()
    client.force_authenticate(user=user_factory())
    return client
class OrderTest:
    def __init__(self, options, stdout_success):
        self.client = APIClient()
        self.stdout = stdout_success

        self.action = options.get('action')
        organization_name = options.get('organization')
        offering_uuid = options.get('offering')
        attributes_path = options.get('attributes')
        self.attributes = {}

        if attributes_path:
            with open(attributes_path) as attributes_file:
                attributes = attributes_file.read()
                self.attributes = json.loads(attributes)

        try:
            self.offering = marketplace_models.Offering.objects.get(
                uuid=offering_uuid)
        except marketplace_models.Offering.DoesNotExist:
            raise OrderTestException('Offering does not exist.')

        try:
            self.customer = structure_models.Customer.objects.get(
                name=organization_name)
            self.project = structure_models.Project.objects.get(
                customer=self.customer)
            self.owner = self.customer.get_owners().first()
            self.admin = self.project.get_users(
                role=structure_models.ProjectRole.ADMINISTRATOR).first()
        except structure_models.Customer.DoesNotExist:
            self.customer = structure_factories.CustomerFactory(
                name=organization_name)
            self.owner = structure_factories.UserFactory(username='******')
            self.customer.add_user(self.owner,
                                   structure_models.CustomerRole.OWNER)
            self.project = structure_factories.ProjectFactory(
                customer=self.customer)
            self.admin = structure_factories.UserFactory(username='******')
            self.project.add_user(self.admin,
                                  structure_models.ProjectRole.ADMINISTRATOR)
            self.stdout('Organization is created.')

        for i in range(1, 2 - self.offering.plans.count()):
            factories.PlanFactory(offering=self.offering)

        self.plan_1 = self.offering.plans.first()
        self.plan_2 = self.offering.plans.last()

    @property
    def order_item(self):
        order_item_queryset = marketplace_models.OrderItem.objects.filter(
            offering=self.offering, order__project=self.project)
        if order_item_queryset.exists():
            return order_item_queryset.last()

    @property
    def order(self):
        if self.order_item:
            return self.order_item.order

    @contextlib.contextmanager
    def mute_stdout(self):
        stdout = self.stdout
        self.stdout = lambda x: x
        try:
            yield {}
        finally:
            self.stdout = stdout

    def get_request_type(self):
        choices = marketplace_models.RequestTypeMixin.Types.CHOICES
        return filter(lambda x: x[0] == self.order_item.type,
                      choices)[0][1].lower()

    def get_issue(self):
        if self.get_request_type() == 'create':
            return self.order_item.resource.scope.issue
        else:
            ct = ContentType.objects.get_for_model(
                marketplace_models.OrderItem)
            return support_models.Issue.objects.get(
                resource_content_type=ct,
                resource_object_id=self.order_item.pk)

    def get_response(
        self,
        user,
        url_name,
        data=None,
        action=None,
        uuid=None,
        status_code=status.HTTP_200_OK,
    ):
        if uuid:
            url = 'http://localhost%s' % reverse(url_name,
                                                 kwargs={'uuid': uuid})
        else:
            url = 'http://localhost%s' % reverse(url_name)

        if action:
            url += action + '/'

        self.client.force_authenticate(user)
        response = self.client.post(url, data)

        if response.status_code != status_code:
            raise OrderTestException('Request %s failed. %s' %
                                     (action, response.rendered_content))

        return response

    def approve_order(self):
        self.get_response(
            self.owner,
            'marketplace-order-detail',
            action='approve',
            uuid=self.order.uuid,
        )
        process_order_item(self.order_item, self.owner)

        self.stdout('A %s order has been approved.' % self.get_request_type())
        self.stdout('Order UUID: %s' % self.order.uuid)
        self.stdout('Request UUID: %s' % self.order_item.resource.scope.uuid)
        issue = self.get_issue()
        self.stdout('Issue UUID: %s, PK: %s' % (issue.uuid.hex, issue.pk))

    def validate_order_done(self):
        if self.order.state != marketplace_models.Order.States.DONE:
            raise OrderTestException('An order is not done.')

    def validate_request_state(self, issue_resolved, request_state,
                               request_type):
        if (request_type == 'create' and issue_resolved
                and request_state == support_models.Offering.States.OK):
            return

        if (request_type == 'create' and not issue_resolved and request_state
                == support_models.Offering.States.TERMINATED):
            return

        if request_type == 'terminate' and issue_resolved and request_state is None:
            return

        if (request_type == 'terminate' and not issue_resolved
                and request_state == support_models.Offering.States.OK):
            return

        if (request_type == 'update'
                and request_state == support_models.Offering.States.OK):
            return

        raise OrderTestException('Request state is wrong.')

    def issue_info(self):
        if self.order.state == marketplace_models.Order.States.EXECUTING:
            self.stdout('STEP 2: resolve or cancel an issue.')
            self.stdout('A %s order UUID: %s' %
                        (self.get_request_type(), self.order.uuid))
            self.stdout('Request UUID: %s' %
                        self.order_item.resource.scope.uuid)
            issue = self.get_issue()
            self.stdout('Issue UUID: %s, PK: %s' % (issue.uuid.hex, issue.pk))
            self.stdout('Please, resolve or cancel an issue.')

        if self.order.state == marketplace_models.Order.States.DONE:
            issue = self.get_issue()

            if issue.resolved is None:
                raise OrderTestException(
                    'An order is done, but the issue is not resolved or canceled.'
                )
            elif issue.resolved:
                self.stdout('FINISH: A %s order has been resolved.' %
                            self.get_request_type())
            else:
                self.stdout('FINISH: A %s order has been canceled.' %
                            self.get_request_type())

            if self.order_item.resource.scope:
                self.stdout('Request state is: %s.' %
                            self.order_item.resource.scope.state)
            else:
                self.stdout('Request with ID %s has been deleted.' %
                            self.order_item.resource.object_id)

            self.stdout('Resource plan is: %s' %
                        self.order_item.resource.plan.name)

            request_state = (self.order_item.resource.scope
                             and self.order_item.resource.scope.state)
            self.validate_request_state(issue.resolved, request_state,
                                        self.get_request_type())

        if self.order.state == marketplace_models.Order.States.REJECTED:
            self.stdout('A %s order has been rejected.' %
                        self.get_request_type())

        if self.order.state == marketplace_models.Order.States.ERRED:
            self.stdout('A %s order has failed.' % self.get_request_type())

    def create_request(self):
        self.stdout('STEP 1: Make an order.')
        data = {
            'project':
            'http://localhost' +
            reverse('project-detail', kwargs={'uuid': self.project.uuid}),
            'items': [
                {
                    'offering':
                    'http://localhost' + reverse(
                        'marketplace-offering-detail',
                        kwargs={'uuid': self.offering.uuid},
                    ),
                    'attributes':
                    self.attributes,
                    'limits': {},
                    'plan':
                    'http://localhost' +
                    reverse('marketplace-plan-detail',
                            kwargs={'uuid': self.plan_1.uuid}),
                },
            ],
        }

        self.get_response(
            self.admin,
            'marketplace-order-list',
            data=data,
            status_code=status.HTTP_201_CREATED,
        )
        self.approve_order()

    def choice_step(func):
        def wrapped(self):
            if self.order_item:
                self.issue_info()
            else:
                func(self)

        return wrapped

    @choice_step
    def create(self):
        self.create_request()

    @choice_step
    def terminate(self):
        self.stdout('STEP 1: Make an order to terminate a resource.')
        with self.mute_stdout():
            self.create_request()
            self.order_item.resource.scope.issue.set_resolved()

        self.validate_order_done()
        self.get_response(
            self.admin,
            'marketplace-resource-detail',
            action='terminate',
            uuid=self.order_item.resource.uuid,
        )
        self.approve_order()

    @choice_step
    def update(self):
        self.stdout('STEP 1: Make an order to switch plan of a resource.')
        with self.mute_stdout():
            self.create_request()
            self.order_item.resource.scope.issue.set_resolved()

        self.validate_order_done()
        self.stdout('Resource plan is: %s' %
                    self.order_item.resource.plan.name)
        data = {
            'plan':
            'http://localhost' + reverse('marketplace-plan-detail',
                                         kwargs={'uuid': self.plan_2.uuid}),
        }
        self.get_response(
            self.admin,
            'marketplace-resource-detail',
            data=data,
            action='switch_plan',
            uuid=self.order_item.resource.uuid,
        )

        self.approve_order()

    def delete(self):
        order_item_queryset = marketplace_models.OrderItem.objects.filter(
            offering=self.offering, order__project=self.project)
        if not order_item_queryset.exists():
            self.stdout('The order has already been deleted.')
            return

        for order_item in order_item_queryset.all():
            order_item.order.delete()

        self.stdout('Order has been deleted.')

    def run(self):
        getattr(self, self.action, lambda: None)()
class PrivateRecipeApiTest(TestCase):
    """Test unauthenticated recipe api access"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create(email='*****@*****.**',
                                                    password='******')
        self.client.force_authenticate(self.user)

    def test_retrieve_recipe(self):
        """"Test retrieving a list of recipes"""
        sample_recipe(user=self.user)
        sample_recipe(user=self.user)
        res = self.client.get(RECIPE_URL)

        recipe = Recipe.objects.all()
        serializer = RecipeSerializer(recipe, many=True)

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

    def test_recipes_limited_to_user(self):
        """Test retrieving recipes for user"""
        sample_recipe(user=self.user)
        user2 = get_user_model().objects.create(email='*****@*****.**',
                                                password='******')
        sample_recipe(user=user2)
        recipe = Recipe.objects.filter(user=self.user)
        serializer = RecipeSerializer(recipe, many=True)

        res = self.client.get(RECIPE_URL)
        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_detail(self):
        """Test viewing recipe detail"""
        recipe = sample_recipe(user=self.user)
        recipe.tag.add(sample_tag(user=self.user))
        recipe.ingredient.add(sample_ingredient(user=self.user))

        res = self.client.get(detail_url(recipe.pk))
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        serializer = RecipeDetailSerializer(recipe)
        self.assertEqual(res.data, serializer.data)

    def test_create_basic_recipe(self):
        """Test creating a recipe"""
        payload = {'title': 'chocolate cake', 'time': 10, 'price': 15.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'])
        for key in payload.keys():
            self.assertEqual(payload[key], getattr(recipe, key))

    def test_create_recipe_with_tag(self):
        """Test creating recipe with tags"""
        tag1 = sample_tag(user=self.user, name='italian')
        tag2 = sample_tag(user=self.user, name='pasta')
        payload = {
            'title': 'pasta alfredo',
            'time': 10,
            'price': 15.00,
            'tag': [tag2.id, tag1.id]
        }
        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.tag.all()
        self.assertEqual(tags.count(), 2)
        self.assertIn(tag1, tags)
        self.assertIn(tag2, tags)

    def test_create_recipe_with_ingredient(self):
        """Test creating recipe with ingredient"""
        ingredient1 = sample_ingredient(user=self.user, name="salt")
        ingredient2 = sample_ingredient(user=self.user, name="tomato")

        payload = {
            'title': 'pasta',
            'time': 20,
            'price': 10.00,
            'ingredient': [ingredient1.id, ingredient2.id]
        }
        res = self.client.post(RECIPE_URL, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        recipe = Recipe.objects.get(id=res.data['id'])
        ingredients = recipe.ingredient.all()
        self.assertEqual(ingredients.count(), 2)
        self.assertIn(ingredient1, ingredients)
        self.assertIn(ingredient2, ingredients)

    def test_partial_update_recipe(self):
        """"Test updating recipe with patch"""
        recipe = sample_recipe(user=self.user)
        recipe.tag.add(sample_tag(user=self.user))
        new_tag = sample_tag(user=self.user, name='chinese')
        payload = {'title': 'italian pizza', 'tag': [new_tag.id]}
        res = self.client.patch(detail_url(recipe.id), payload)

        recipe.refresh_from_db()
        self.assertEqual(res.data['title'], payload['title'])

        tags = recipe.tag.all()
        self.assertEqual(len(tags), 1)
        self.assertIn(new_tag, tags)

    def test_full_update_recipe(self):
        """Test updating recipe with put"""
        recipe = sample_recipe(user=self.user)
        recipe.tag.add(sample_tag(user=self.user))
        recipe.ingredient.add(sample_ingredient(user=self.user))
        new_ingredient = sample_ingredient(user=self.user, name='cream')
        new_tag = sample_tag(user=self.user, name='iran')
        payload = {
            'title': 'ghorme sabzi',
            'time': 24,
            'price': 500.00,
            'tag': [new_tag.id],
            'ingredient': [new_ingredient.id]
        }
        self.client.put(detail_url(recipe.id), payload)
        recipe.refresh_from_db()
        tags = recipe.tag.all()
        ingredients = recipe.ingredient.all()
        self.assertEqual(len(tags), 1)
        self.assertEqual(len(ingredients), 1)
        self.assertEqual(recipe.price, payload['price'])
        self.assertEqual(recipe.title, payload['title'])
Пример #58
0
 def make():
     client = APIClient()
     client.force_authenticate(user=user_factory())
     return client
class RecipeImageUploadTest(TestCase):
    """Test for uploading image"""
    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user(email='*****@*****.**',
                                                         password='******')
        self.client.force_authenticate(self.user)
        self.recipe = sample_recipe(user=self.user)

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

    def tes_uploading_image_recipe(self):
        """test uploading an image to recipe"""
        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(image_upload_url(self.recipe.id),
                                   {'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_request(self):
        """Test uploading invalid an image"""
        res = self.client.post(image_upload_url(self.recipe.id),
                               {'image': 'not image'},
                               format='multipart')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_filter_recipes_by_tags(self):
        """Test returning recipes with specific tags"""
        recipe1 = sample_recipe(user=self.user, title='thai food')
        recipe2 = sample_recipe(user=self.user, title='burger')
        tag1 = sample_tag(user=self.user, name='persian')
        tag2 = sample_tag(user=self.user, name='thailand')
        recipe1.tag.add(tag1)
        recipe2.tag.add(tag2)
        recipe3 = sample_recipe(user=self.user, title='fish and chips')

        res = self.client.get(RECIPE_URL, {'tag': f'{tag1.id}, {tag2.id}'})
        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)

        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)

    def test_filter_recipes_by_ingredient(self):
        """Test returning recipes with specific ingredient"""
        recipe1 = sample_recipe(user=self.user, title='thai food')
        recipe2 = sample_recipe(user=self.user, title='burger')
        recipe3 = sample_recipe(user=self.user, title='fish and chips')
        ingredient1 = sample_ingredient(user=self.user, name='salt')
        ingredient2 = sample_ingredient(user=self.user, name='carry')

        recipe1.ingredient.add(ingredient1)
        recipe2.ingredient.add(ingredient2)

        serializer1 = RecipeSerializer(recipe1)
        serializer2 = RecipeSerializer(recipe2)
        serializer3 = RecipeSerializer(recipe3)

        res = self.client.get(
            RECIPE_URL, {'ingredient': f'{ingredient1.id},{ingredient2.id}'})
        self.assertIn(serializer1.data, res.data)
        self.assertIn(serializer2.data, res.data)
        self.assertNotIn(serializer3.data, res.data)
Пример #60
0
class PrivateTagsApiTests(TestCase):
    """Test the authorized user tags 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_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 = 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('*****@*****.**',
                                                     'test123')
        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 = TagSerializer(tag1)
        serializer2 = 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 return unique items"""
        tag = Tag.objects.create(user=self.user, name='Breakfast')
        Tag.objects.create(user=self.user, name='Lunch')
        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)