class TestCategoryDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True for index in range(10): Category.objects.create(name='category{}'.format(index)) @use_cache() def test_admin(self): """ Tests that only the following db queries are done: * 4 requests to get the session an the request user with its permissions and * 2 requests to get the list of all categories. """ self.client.force_login(get_user_model().objects.get(pk=1)) with self.assertNumQueries(6): self.client.get(reverse('category-list')) @use_cache() def test_anonymous(self): """ Tests that only the following db queries are done: * 3 requests to get the permission for anonymous (config and permissions) * 2 requests to get the list of all motions and """ with self.assertNumQueries(5): self.client.get(reverse('category-list'))
class TestWorkflowDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True # There do not need to be more workflows @use_cache() def test_admin(self): """ Tests that only the following db queries are done: * 4 requests to get the session an the request user with its permissions, * 2 requests to get the list of all workflows, * 1 request to get all states and * 1 request to get the next states of all states. """ self.client.force_login(get_user_model().objects.get(pk=1)) with self.assertNumQueries(8): self.client.get(reverse('workflow-list')) @use_cache() def test_anonymous(self): """ Tests that only the following db queries are done: * 3 requests to get the permission for anonymous, * 2 requests to get the list of all workflows, * 1 request to get all states and * 1 request to get the next states of all states. """ with self.assertNumQueries(7): self.client.get(reverse('workflow-list'))
class TestCharmessageDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True user = User.objects.get(pk=1) for index in range(10): ChatMessage.objects.create(user=user) @use_cache() def test_admin(self): """ Tests that only the following db queries are done: * 4 requests to get the session an the request user with its permissions, * 2 requests to get the list of all chatmessages, """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(6): self.client.get(reverse('chatmessage-list'))
class TestDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config["general_system_enable_anonymous"] = True for index in range(10): Mediafile.objects.create( title="some_file{}".format(index), mediafile=SimpleUploadedFile("some_file{}".format(index), b"some content."), ) def test_admin(self): """ Tests that only the following db queries are done: * 5 requests to get the session an the request user with its permissions and * 2 requests to get the list of all files. """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(7): self.client.get(reverse("mediafile-list")) def test_anonymous(self): """ Tests that only the following db queries are done: * 2 requests to get the permission for anonymous (config and permissions) and * 2 requests to get the list of all projectors. """ with self.assertNumQueries(4): self.client.get(reverse("mediafile-list"))
class TestTagDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True config.save_default_values() for index in range(10): Tag.objects.create(name='tag{}'.format(index)) def test_admin(self): """ Tests that only the following db queries are done: * 5 requests to get the session an the request user with its permissions, * 1 requests to get the list of all tags, """ self.client.force_login(User.objects.get(pk=1)) get_redis_connection("default").flushall() with self.assertNumQueries(6): self.client.get(reverse('tag-list')) def test_anonymous(self): """ Tests that only the following db queries are done: * 1 requests to see if anonyomus is enabled * 1 requests to get the list of all projectors, """ get_redis_connection("default").flushall() with self.assertNumQueries(2): self.client.get(reverse('tag-list'))
class TestViewSetUser(TransactionTestCase): fixtures = [ 'users.json', ] def setUp(self): super(TestViewSetUser, self).setUp() self.client = APIClient() def test_http_get(self): user = User.objects.get(pk=1) self.client.force_login(user) response = self.client.get('/0/sessions/') expected = json.loads(response.content) self.assertEquals(200, response.status_code) self.assertEquals(1, len(expected)) self.assertEquals(1, expected[0]['id']) self.client.logout() def test_http_get_not_logged_in(self): response = self.client.get('/0/sessions/') expected = json.loads(response.content) self.assertEquals(200, response.status_code) self.assertEquals(0, len(expected))
class TestConfigDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True def test_admin(self): """ Tests that only the following db queries are done: * 2 requests to get the session an the request user with its permissions and * 1 requests to get the list of all config values """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(3): self.client.get(reverse('config-list')) def test_anonymous(self): """ Tests that only the following db queries are done: * 2 requests to get the permission for anonymous (config and permissions), * 1 to get all config value and * 57 requests to find out if anonymous is enabled. TODO: The last 57 requests are a bug. """ with self.assertNumQueries(63): self.client.get(reverse('config-list'))
class TestUserStackRecordView(TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() User = get_user_model() cls.default_user, _ = User.objects.get_or_create(username='******') UserSupplementStackFixturesGenerator.create_fixtures(cls.default_user) cls.url = reverse('record-supplement-stack') def setUp(self): self.client = APIClient() self.client.force_login(self.default_user) def test_stack_record_view(self): stack = UserSupplementStack.objects.all().first() data = { 'stack_uuid': str(stack.uuid) } response = self.client.post(self.url, data=data, format='json') self.assertEqual(response.status_code, 201, response.data) def test_stack_record_events_correctly(self): original_log_count = SupplementLog.objects.filter(user=self.default_user).count() stack = UserSupplementStack.objects.all().first() data = { 'stack_uuid': str(stack.uuid) } response = self.client.post(self.url, data=data, format='json') self.assertEqual(response.status_code, 201, response.data) expected_log_size = original_log_count + stack.compositions.count() updated_log_count = SupplementLog.objects.filter(user=self.default_user).count() self.assertEqual(expected_log_size, updated_log_count) def test_stack_record_log_records_will_not_duplicate(self): original_log_count = SupplementLog.objects.filter(user=self.default_user).count() stack = UserSupplementStack.objects.all().first() data = { 'stack_uuid': str(stack.uuid), 'time': get_current_utc_time_and_tz().isoformat() } response = self.client.post(self.url, data=data, format='json') self.assertEqual(response.status_code, 201, response.data) # now post this multiple times to make sure won't duplicate self.client.post(self.url, data=data, format='json') self.client.post(self.url, data=data, format='json') expected_log_size = original_log_count + stack.compositions.count() updated_log_count = SupplementLog.objects.filter(user=self.default_user).count() self.assertEqual(expected_log_size, updated_log_count) def test_invalid_stack_record_view(self): data = { 'stack_uuid': '1234' } response = self.client.post(self.url, data=data, format='json') self.assertEqual(response.status_code, 400, response.data)
class GroupTest(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user( username='******', email='*****@*****.**', password='******') self.client = APIClient() self.client.force_login(user=self.user) def test_detail_group_create(self): response = self.client.post( '/api/users/banifest/groups/', { 'color': 'GREEN', 'priority': 2, 'name': 'test', }, format='json') self.assertEqual(response.status_code, 201) def test_detail_group_update_auth(self): response = self.client.post( '/api/users/banifest/groups/', { 'color': 'GREEN', 'priority': 2, 'name': 'test', }, format='json') response = self.client.patch( '/api/users/banifest/groups/{0}/'.format(response.data['id']), { 'name': 'NotTest', 'color': 'RED', 'priority': -1 }, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['name'], 'NotTest') self.assertEqual(response.data['color'], 'RED') self.assertEqual(response.data['priority'], -1) def test_detail_group_delete_auth(self): response = self.client.post( '/api/users/banifest/groups/', { 'color': 'GREEN', 'priority': 2, 'name': 'test', }, format='json') response = self.client.delete( '/api/users/banifest/groups/{0}/'.format(response.data['id']), format='json') self.assertEqual(response.status_code, 204) def test_list_group_with_auth(self): response = self.client.get('/api/users/banifest/groups/', format='json') self.assertEqual(response.status_code, 200) def test_list_group_without_auth(self): client = APIClient() response = client.get('/api/users/banifest/groups/', format='json') self.assertEqual(response.status_code, 403)
class TestAPI(AppTestCase): fixtures = ['wip/tests/fixtures/test.yaml'] def setUp(self): self.user = self.create_user() self.client = APIClient() self.client.force_login(self.user) self.base_url = reverse('api:jobrelationship-list') self._create_test_object() def _create_test_object(self): self.test_object = JobRelationship.objects.first() self.test_object_data = JobRelationshipSerializer( instance=self.test_object).data self.test_object_url = self.base_url + str(self.test_object.pk) + '/' def test_filter_class(self): self.assertEqual(JobRelationshipViewSet.filter_class, JobRelationshipFilter) def test_list(self): response = self.client.get(self.base_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), [self.test_object_data]) def test_post(self): del self.test_object_data['id'] self.test_object_data['user'] = self.user.pk response = self.client.post(self.base_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.test_object_data['user_id'] = self.test_object_data.pop('user') self.test_object_data['relationship_id'] = self.test_object_data.pop( 'relationship') JobRelationship.objects.get(**self.test_object_data) def test_detail(self): response = self.client.get(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), self.test_object_data) def test_put(self): self.test_object_data['user'] = self.user.pk response = self.client.put(self.test_object_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.test_object_data['user_id'] = self.test_object_data.pop('user') self.test_object_data['relationship_id'] = self.test_object_data.pop( 'relationship') JobRelationship.objects.get(**self.test_object_data) def test_delete(self): response = self.client.delete(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(JobRelationship.DoesNotExist): JobRelationship.objects.get(pk=self.test_object.pk)
class WriteUpFlaggedPromptViewTests(TestCase): VIEW_NAME = WriteUpResourceEndpoints.PROMPT_FLAGS @classmethod def setUpTestData(cls): registered_user = UserFactory(is_staff=False) cls.registered_user_id = registered_user.id staff_user = UserFactory(is_staff=True) cls.staff_user_id = staff_user.id def setUp(self): self.unregistered_user_client = APIClient() self.registered_user = User.objects.get(id=self.registered_user_id) self.registered_user_client = APIClient() self.registered_user_client.force_login(self.registered_user) self.staff_user = UserFactory(is_staff=True) self.staff_user_client = APIClient() self.staff_user_client.force_login(self.staff_user) def test_view(self): prompt = WriteUpPromptFactory() data_kwargs = {"prompt_uuid": prompt.uuid_str} url = reverse(self.VIEW_NAME, kwargs=data_kwargs) response = self.registered_user_client.post(url) self.assertEqual(response.status_code, 200) def test_post_view_multiple_times_only_results_in_one(self): prompt = WriteUpPromptFactory() data_kwargs = {"prompt_uuid": prompt.uuid_str} url = reverse(self.VIEW_NAME, kwargs=data_kwargs) for _ in range(3): self.registered_user_client.post(url) instance_count = WriteUpFlaggedPrompt.objects.filter( user=self.registered_user, prompt=prompt).count() self.assertEqual(instance_count, 1) def test_view_delete(self): prompt = WriteUpPromptFactory() WriteUpFlaggedPromptFactory(user=self.registered_user, prompt=prompt) data_kwargs = {"prompt_uuid": prompt.uuid_str} url = reverse(self.VIEW_NAME, kwargs=data_kwargs) response = self.registered_user_client.delete(url) self.assertEqual(response.status_code, 204) def test_view_delete_doesnt_exist(self): data_kwargs = {"prompt_uuid": generate_random_uuid_as_string()} url = reverse(self.VIEW_NAME, kwargs=data_kwargs) response = self.registered_user_client.delete(url) self.assertEqual(response.status_code, 404)
def test_user_card_add(self): token = Token.objects.get(user_id=self.test_account.id) client = APIClient() client.force_login(self.test_account) client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) response = client.post('/api/card-add', json.dumps({"business_id": self.business.id}), content_type='application/json') self.assertEqual(response.status_code, 200)
def test_user_with_wallet(self): wallet = WalletFactory.create() user = wallet.user client = APIClient() client.force_login(user) response = client.get(reverse('api_v1:users:wallet')) assert response.status_code == 200
def test_poll_detail_API_GET_with_empty_options_poll(self): empty_poll = PollQuestion.objects.create(question='empty poll', user=self.owner) c = APIClient() c.force_login(user=self.auth_user) response = c.get(reverse('api_poll_detail', kwargs={'question': empty_poll.id}), content_type='application/json') self.assertEqual(response.status_code, 404)
def test_poll_detail_API_GET_with_authentication(self): c = APIClient() c.force_login(user=self.auth_user) response = c.get(self.url) poll_option = PollOption.objects.filter(question=self.question) serializer = PollOptionSerializer(poll_option, many=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, serializer.data)
def test_poll_question_API_PUT_with_invalid_data(self): c = APIClient() c.force_login(user=self.auth_user) response = c.put(self.url, {'close': 'invalid'}, content_type='application/json') self.assertEqual(response.status_code, 400) self.assertEqual( PollQuestion.objects.get(pk=self.question.id).close, False)
def test_duplicate_aliases(self, user_factory, alias_factory): user = user_factory(username="******", search_enabled=True) alias_factory(user=user, name="Search Daly") alias_factory(user=user, name="Search Nolan") client = APIClient() client.force_login(user) response = client.get("/search/", {"q": "Search"}) soup = BeautifulSoup(response.content, "html.parser") assert len(soup.find_all(class_="card")) == 1
def test_model_permission_viewset(self): """ Test GenericDjangoViewsetPermissions """ client = APIClient() client.force_login(self.user) def test_methods(with_grant_permission: Optional[str] = None, should_succeed: Set = set()): turtle_id = self.turtle.id with transaction.atomic(): if with_grant_permission: self.grant_permission(with_grant_permission) response = client.get(reverse('permissions:model-list')) self.assertEqual(response.status_code, 200 if "view" in should_succeed else 403) response = client.get( reverse('permissions:model-detail', kwargs={"pk": turtle_id})) self.assertEqual(response.status_code, 200 if "view" in should_succeed else 403) response = client.post(reverse('permissions:model-list'), data={ "name": "leonardo", "color": "blue", "shell_size": "13.0" }) self.assertEqual(response.status_code, 201 if "add" in should_succeed else 403) response = client.patch(reverse('permissions:model-detail', kwargs={"pk": turtle_id}), data={"name": "michaelangelo"}) self.assertEqual(response.status_code, 200 if "change" in should_succeed else 403) response = client.delete( reverse('permissions:model-detail', kwargs={"pk": turtle_id})) self.assertEqual(response.status_code, 204 if "delete" in should_succeed else 403) transaction.set_rollback(True) test_methods() test_methods("view_ninjaturtlemodel", {"view"}) test_methods("add_ninjaturtlemodel", {"add"}) test_methods("change_ninjaturtlemodel", {"change"}) test_methods("delete_ninjaturtlemodel", {"delete"})
class ReferenceTest(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.group = Group.objects.create(color='GREEN', priority=1, name='test', user=self.user) self.ref = Reference.objects.create(name='GREEN', ref_url='http://123.com', group=self.group, user=self.user) self.client = APIClient() self.client.force_login(user=self.user) def test_detail_ref_create(self): response = self.client.post('/api/users/banifest/references/', { 'name': 'test', 'ref_url': 'http://test.com', 'group': self.group.id }, format='json') self.assertEqual(response.status_code, 201) def test_detail_ref_update_auth(self): response = self.client.patch( '/api/users/banifest/references/{0}/'.format(self.ref.id), { 'name': 'NotTest', 'ref_url': 'http://Not-test.com', }, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['name'], 'NotTest') self.assertEqual(response.data['ref_url'], 'http://Not-test.com') def test_detail_user_delete_auth(self): response = self.client.delete( '/api/users/banifest/references/{0}/'.format(self.ref.id), format='json') self.assertEqual(response.status_code, 204) def test_list_ref_with_auth(self): response = self.client.get('/api/users/banifest/references/', format='json') self.assertEqual(response.status_code, 200) def test_detail_ref_with_auth(self): response = self.client.get('/api/users/banifest/references/', format='json') self.assertEqual(response.status_code, 200) def test_list_ref_without_auth(self): client = APIClient() response = client.get('/api/users/', format='json') self.assertEqual(response.status_code, 403)
class SemesterWithFutureCourseTestCase(TestCase, PCRTestMixin): def setUp(self): set_semester() AddDropPeriod(semester="2012A").save() AddDropPeriod(semester="3008C").save() self.instructor_name = "Instructor One" self.client = APIClient() self.client.force_login(User.objects.create_user(username="******")) create_review("CIS-120-001", TEST_SEMESTER, self.instructor_name, {"instructor_quality": 4}) create_review("CIS-120-001", "2012A", self.instructor_name, {"instructor_quality": 2}) create_review( "CIS-120-002", "2007C", self.instructor_name, {"instructor_quality": 0}, responses=0, ) create_review( "CIS-120-001", "2007C", "No Responses Instructor", {"instructor_quality": 0}, responses=0, ) create_review("CIS-160-001", "3008C", self.instructor_name, {"instructor_quality": 2}) def test_course(self): self.assertRequestContainsAppx( "course-reviews", "CIS-120", { "num_semesters": 3, **average_and_recent(3, 4), "instructors": { Instructor.objects.get(name=self.instructor_name).pk: { **average_and_recent(3, 4), "latest_semester": TEST_SEMESTER, } }, }, ) def test_department(self): self.assertRequestContainsAppx( "department-reviews", "CIS", { "courses": { "CIS-120": average_and_recent(3, 4), "CIS-160": average_and_recent(2, 2), } }, )
class TestDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some agenda items are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True for index in range(10): Topic.objects.create(title='topic{}'.format(index)) parent = Topic.objects.create(title='parent').agenda_item child = Topic.objects.create(title='child').agenda_item child.parent = parent child.save() Motion.objects.create(title='motion1') Motion.objects.create(title='motion2') Assignment.objects.create(title='assignment', open_posts=5) def test_admin(self): """ Tests that only the following db queries are done: * 7 requests to get the session an the request user with its permissions, * 1 requests to get the list of all agenda items, * 1 request to get all speakers, * 3 requests to get the assignments, motions and topics and * 1 request to get an agenda item (why?) * 2 requests for the motionsversions. TODO: The last two request for the motionsversions are a bug. """ self.client.force_login(User.objects.get(pk=1)) get_redis_connection("default").flushall() with self.assertNumQueries(15): self.client.get(reverse('item-list')) def test_anonymous(self): """ Tests that only the following db queries are done: * 3 requests to get the permission for anonymous, * 1 requests to get the list of all agenda items, * 1 request to get all speakers, * 3 requests to get the assignments, motions and topics and * 1 request to get an agenda item (why?) * 2 requests for the motionsversions. TODO: The last two request for the motionsversions are a bug. """ get_redis_connection("default").flushall() with self.assertNumQueries(11): self.client.get(reverse('item-list'))
class APIFSTestCase(TestCase): """ API tests that require FS. """ @classmethod def setUpTestData(cls): cls.user = User.objects.create(email='*****@*****.**') def setUp(self): self.client = APIClient() self.client.force_login(self.user) def test_upload_download(self): with mock.patch('main.models.User.get_clients', MockClients(self.user).get_clients): # TODO: I would like to test multipart upload as well. r = self.client.post( reverse('api:files_data_path', args=('/foo',)), {'file': BytesIO(TEST_FILE_BODY)}) self.assertEqual(200, r.status_code) # TODO: I cannot figure out how to post multipart and receive JSON # self.assertEqual(15, len(r.json())) # A file object should now exist, we can access it by path. r = self.client.get(reverse('api:files_data_path', args=('/foo',)), {'format': 'json'}) self.assertEqual(200, r.status_code) self.assertEqual(TEST_FILE_BODY, b''.join(list(r.streaming_content))) # A file object should now exist, we can access it by uid. file = UserFile.objects.first() r = self.client.get(reverse('api:files_data_uid', args=(file.uid,)), {'format': 'json'}) self.assertEqual(200, r.status_code) self.assertEqual(TEST_FILE_BODY, b''.join(list(r.streaming_content))) # Ensure we can download a specific version of a file. r = self.client.get(reverse('api:files_version_data_path', args=(file.path, file.file.version.uid)), {'format': 'json'}) self.assertEqual(200, r.status_code) self.assertEqual(TEST_FILE_BODY, b''.join(list(r.streaming_content))) # Ensure we can download a specific version of a file by uid. r = self.client.get(reverse('api:files_version_data_uid', args=(file.uid, file.file.version.uid)), {'format': 'json'}) self.assertEqual(200, r.status_code) self.assertEqual(TEST_FILE_BODY, b''.join(list(r.streaming_content)))
def test_view_no_data(self): new_user, _ = User.objects.get_or_create(username='******') client = APIClient() client.force_login(new_user) response = client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 0)
class TestAPI(AppTestCase): fixtures = ['wip/tests/fixtures/test.yaml'] def setUp(self): self.user = self.create_user() self.client = APIClient() self.client.force_login(self.user) self.base_url = reverse('api:task-list') self._create_test_object() def _create_test_object(self): self.test_object = Task.objects.first() self.test_object_data = TaskSerializer(instance=self.test_object).data self.test_object_url = self.base_url + str(self.test_object.pk) + '/' def test_filter_class(self): self.assertEqual(TaskViewSet.filter_class, TaskFilter) def test_list(self): response = self.client.get(self.base_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), [self.test_object_data]) def test_post(self): del self.test_object_data['id'] del self.test_object_data['created_at'] del self.test_object_data['created_by'] del self.test_object_data['is_overdue'] self.test_object_data['title'] = 'some title' response = self.client.post(self.base_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.test_object_data['job_id'] = self.test_object_data.pop('job') Task.objects.get(**self.test_object_data) def test_detail(self): response = self.client.get(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), self.test_object_data) def test_put(self): del self.test_object_data['created_at'] del self.test_object_data['is_overdue'] self.test_object_data['title'] = 'some title' response = self.client.put(self.test_object_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.test_object_data['job_id'] = self.test_object_data.pop('job') Task.objects.get(**self.test_object_data) def test_delete(self): response = self.client.delete(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(Task.DoesNotExist): Task.objects.get(pk=self.test_object.pk)
def test_create_channel_normal_user(mocker, patched_users_api): """If a user is not a superuser they should get a forbidden status""" client = APIClient() user = UserFactory.create() client.force_login(user) program = RoleFactory.create().program add_channel_mock = mocker.patch('discussions.serializers.add_channel', return_value={}, autospec=True) resp = client.post(reverse('channel-list'), data=_make_create_channel_input(program.id), format="json") assert add_channel_mock.called is False assert resp.status_code == 403
def test_ipaddress_restriction(self, user_factory, plan_factory): client = APIClient(REMOTE_ADDR="8.8.8.8") user = user_factory(is_staff=True) client.force_login(user) client.user = user plan = plan_factory() response = client.get(f"http://testserver/admin/rest/plans/{plan.id}") assert response.status_code == 400
def run(): user = User.objects.get(email="*****@*****.**") url = reverse("rest_password_reset") client = APIClient() client.force_login(user) data = {"email": user.email} response = client.post(url, data=data)
def test_getting_of_phone_number(self): phone_number = '+16175555555' client = APIClient() client.force_login(self.test_user) UserPhoneNumberDetails.objects.create(user=self.test_user, phone_number=phone_number) response = client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['phone_number'], phone_number)
def test_create_channel_staff_non_superuser(mocker, patched_users_api): """a staff role user who is not superuser should also get a forbidden status""" client = APIClient() role = RoleFactory.create(role=Staff.ROLE_ID) client.force_login(role.user) program = role.program add_channel_mock = mocker.patch('discussions.serializers.add_channel', return_value={}, autospec=True) resp = client.post(reverse('channel-list'), data=_make_create_channel_input(program.id), format="json") assert add_channel_mock.called is False assert resp.status_code == 403
def test_logout(self): client = APIClient() client.force_login(self.test_user) response = client.post(reverse("logout")) self.assertEqual(response.status_code, 200) # Try getting a view that needs auth. response = client.get(reverse("rule-list")) self.assertEqual(response.status_code, 403)
def test_poll_question_API_PUT_with_owner_user(self): c = APIClient() c.force_login(user=self.owner) response = c.put(self.url, self.payload, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual( PollQuestion.objects.get(pk=self.question.id).close, True)
def test_search_followed(self, anon_client, user_factory, follow_factory): user = user_factory(username="******", search_enabled=True) followed = user_factory(username="******", search_enabled=False) follow_factory(from_user=user, to_user=followed, nickname="Alex Rodriguez") client = APIClient() client.force_login(user) response = client.get("/search/", {"q": "Rodriguez"}) assert "searchable".encode("utf-8") in response.content
def test_phone_number_nonsense_update(self): client = APIClient() client.force_login(self.test_user) details = { 'phone_number': 'abcde' } response = client.post(self.url, data=details) self.assertEqual(response.status_code, 400)
class ViewTestCase(TestCase): """Test suite for the api views.""" def setUp(self): """Define the test client and other test variables.""" self.client = APIClient() user = User.objects.create(username='******') self.client.force_login(user=user) self.forecast_data = {'date': datetime.date.fromordinal(30),'min_temp':0,'max_temp':25,'wind':5,'rain':10} self.response = self.client.post( reverse('main:create'), self.forecast_data, format='json') def test_api_can_create_a_forecast(self): """Test the api can CREATE a forecast.""" self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) def test_api_can_get_a_forecast(self): """Test the api can GET a forecast.""" forecast = Forecast.objects.get() response = self.client.get( reverse('main:details',kwargs={'pk': forecast.id}) , format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, forecast) def test_api_can_update_a_forecast(self): """Test the api can UPDATE a forecast.""" forecast = Forecast.objects.order_by("date").first() forecast_update = {'date':forecast.date,'min_temp':0,'max_temp':25,'wind':5,'rain':10} response = self.client.put( reverse('main:details', kwargs={'pk': forecast.id}), forecast_update, format='json' ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_api_can_delete_a_forecast(self): """Test the api can DELETE a forecast.""" forecast = Forecast.objects.first() response = self.client.delete( reverse('main:details', kwargs={'pk': forecast.id}), format='json', follow=True) self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) def test_can_load_database(self): load_forecasts() forecast = Forecast.objects.get(date=timezone.now().date()) self.assertEqual(forecast is not None,True)
class TestAPI(AppTestCase): fixtures = ['wip/tests/fixtures/test.yaml'] def setUp(self): self.user = self.create_user() self.client = APIClient() self.client.force_login(self.user) self.base_url = reverse('api:timeentry-list') self._create_test_object() def _create_test_object(self): job = Job.objects.first() self.test_object = TimeEntry.objects.create( task=job.tasks.first(), started_at=make_aware(datetime(2019, 4, 1, 9, 0, 0)), ended_at=make_aware(datetime(2019, 4, 1, 9, 15, 0)), user=self.user, comments='some comments' ) self.test_object_data = TimeEntrySerializer(instance=self.test_object).data self.test_object_url = self.base_url + str(self.test_object.pk) + '/' def test_filter_class(self): self.assertEqual(TimeEntryViewSet.filter_class, TimeEntryFilter) def test_list(self): response = self.client.get(self.base_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), [self.test_object_data]) def test_post(self): del self.test_object_data['id'] del self.test_object_data['duration'] self.test_object_data['comments'] = 'some edited comments' response = self.client.post(self.base_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) TimeEntry.objects.get(**self.test_object_data) def test_detail(self): response = self.client.get(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), self.test_object_data) def test_put(self): del self.test_object_data['duration'] self.test_object_data['comments'] = 'some edited comments' response = self.client.put(self.test_object_url, self.test_object_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) TimeEntry.objects.get(**self.test_object_data) def test_delete(self): response = self.client.delete(self.test_object_url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(TimeEntry.DoesNotExist): TimeEntry.objects.get(pk=self.test_object.pk)
class TwoSectionsOneSemesterTestCase(TestCase, PCRTestMixin): def setUp(self): set_semester() self.instructor_name = "Instructor One" self.client = APIClient() self.client.force_login(User.objects.create_user(username="******")) create_review("CIS-120-001", TEST_SEMESTER, self.instructor_name, {"instructor_quality": 4}) create_review("CIS-120-002", TEST_SEMESTER, self.instructor_name, {"instructor_quality": 2}) def test_course(self): self.assertRequestContainsAppx( "course-reviews", "CIS-120", { "num_semesters": 1, **average_and_recent(3, 3), "instructors": { Instructor.objects.get(name=self.instructor_name).pk: { **average_and_recent(3, 3), "latest_semester": TEST_SEMESTER, }, }, }, ) def test_instructor(self): self.assertRequestContainsAppx( "instructor-reviews", Instructor.objects.get(name=self.instructor_name).pk, { **average_and_recent(3, 3), "num_semesters": 1, "courses": { "CIS-120": average_and_recent(3, 3) }, }, ) def test_department(self): self.assertRequestContainsAppx( "department-reviews", "CIS", {"courses": { "CIS-120": average_and_recent(3, 3) }}) def test_history(self): self.assertRequestContainsAppx( "course-history", ["CIS-120", Instructor.objects.get(name=self.instructor_name).pk], {"sections": [rating(4), rating(2)]}, )
def test_static_cohort_csv_upload(self, patch_calculate_cohort_from_csv): self.team.app_urls = ["http://somewebsite.com"] self.team.save() Person.objects.create(team=self.team, properties={"email": "*****@*****.**"}) Person.objects.create(team=self.team, distinct_ids=["123"]) Person.objects.create(team=self.team, distinct_ids=["456"]) csv = SimpleUploadedFile( "example.csv", str.encode(""" User ID, [email protected], 123 """), content_type="application/csv", ) response = self.client.post( "/api/cohort/", { "name": "test", "csv": csv, "is_static": True }, ) self.assertEqual(response.status_code, 201, response.content) self.assertEqual(patch_calculate_cohort_from_csv.call_count, 1) self.assertFalse(response.json()["is_calculating"], False) self.assertFalse( Cohort.objects.get(pk=response.json()["id"]).is_calculating) csv = SimpleUploadedFile( "example.csv", str.encode(""" User ID, 456 """), content_type="application/csv", ) # A weird issue with pytest client, need to user Rest framework's one # see https://stackoverflow.com/questions/39906956/patch-and-put-dont-work-as-expected-when-pytest-is-interacting-with-rest-framew client = APIClient() client.force_login(self.user) response = client.patch("/api/cohort/%s/" % response.json()["id"], { "name": "test", "csv": csv, }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(patch_calculate_cohort_from_csv.call_count, 2) self.assertFalse(response.json()["is_calculating"], False) self.assertFalse( Cohort.objects.get(pk=response.json()["id"]).is_calculating)
def test_create_channel(description, mocker, patched_users_api): """superuser can create a channel using the REST API""" client = APIClient() role = RoleFactory.create(role=Staff.ROLE_ID) role.user.is_superuser = True role.user.save() client.force_login(role.user) channel = ChannelFactory.create() add_channel_mock = mocker.patch('discussions.serializers.add_channel', return_value=channel, autospec=True) create_channel_input = _make_create_channel_input(role.program.id, description) resp = client.post(reverse('channel-list'), data={ **create_channel_input, "name": channel.name, }, format="json") assert resp.status_code == 201 assert resp.json() == { "name": channel.name, "title": create_channel_input['title'], "description": create_channel_input['description'], "channel_type": create_channel_input['channel_type'], "query": channel.query.query, "program_id": role.program.id, } kwargs = add_channel_mock.call_args[1] assert kwargs['title'] == create_channel_input['title'] assert kwargs['name'] == channel.name assert kwargs['description'] == create_channel_input['description'] assert kwargs['channel_type'] == create_channel_input['channel_type'] assert kwargs['original_search'].to_dict() == { 'query': { 'bool': { 'filter': [ { 'bool': { 'minimum_should_match': 1, 'must': [{'term': {'program.is_learner': True}}], 'should': [{ 'term': {'program.id': role.program.id} }] } }, { 'term': {'profile.filled_out': True} } ] } }, 'size': 50 } assert kwargs['program_id'] == role.program.id
class BracketAPITests(APITestCase): def setUp(self): self.bracket = BracketFactory() self.tournament = TournamentFactory() self.bracket2 = BracketFactory(tournament=self.tournament) self.client = APIClient() self.user = UserFactory(is_superuser=True) self.client.force_login(self.user) def test_can_get_all_brackets(self): response = self.client.get(reverse_lazy('tournament:bracket-list-api')) self.assertEqual(response.status_code, 200) self.assertContains(response, self.bracket.name) self.assertContains(response, self.bracket2.name) def test_can_get_specific_brackets(self): response = self.client.get( reverse_lazy('tournament:bracket-detail-api', kwargs={'pk': self.bracket.pk})) self.assertEqual(response.status_code, 200) self.assertContains(response, self.bracket.name) self.assertNotContains(response, self.bracket2.name) def test_can_edit_bracket(self): data = { 'name': 'bracket_name', 'tournament': self.tournament.id, 'bracket_type': 'w', } response = self.client.put(reverse_lazy( 'tournament:bracket-detail-api', kwargs={'pk': self.bracket.pk}), data=data) self.assertEqual(response.status_code, 200) self.bracket.refresh_from_db() self.assertEqual(self.bracket.name, 'bracket_name') def test_can_post_new_bracket(self): self.assertEqual(Bracket.objects.count(), 2) data = {'name': faker.word(), 'tournament': self.tournament.id} response = self.client.post( reverse_lazy('tournament:bracket-list-api'), data=data) self.assertEqual(response.status_code, 201) self.assertEqual(Bracket.objects.count(), 3) def test_can_delete_bracket(self): self.assertEqual(Bracket.objects.count(), 2) response = self.client.delete( reverse_lazy('tournament:bracket-detail-api', kwargs={'pk': self.bracket.pk})) self.assertEqual(response.status_code, 204) self.assertEqual(Bracket.objects.count(), 1)
def api_user(django_user_model): client = APIClient() username = '******' password = '******' user = django_user_model.objects.create_user(username=username, password=password, is_staff=False) user_token = Token.objects.create(user=user) client.force_login(user) client.credentials(HTTP_AUTHORIZATION=f'Token {user_token.key}') return client
class TestAggregatedSupplementLogViews(TestCase): """ Bunch of subpar tests """ @classmethod def setUpTestData(cls): cls.default_user, _ = User.objects.get_or_create(username='******') builder = DemoHistoricalDataBuilder(cls.default_user) builder.create_historical_fixtures() supplement = Supplement.objects.filter(user=cls.default_user).first() supplement_uuid = str(supplement.uuid) cls.supplement = supplement cls.url = reverse('aggregate-supplement-log', args=[supplement_uuid]) super().setUpTestData() def setUp(self): self.client = APIClient() self.client.force_login(self.default_user) def test_daily_view(self): request_params = { 'frequency': DAILY_FREQUENCY, } response = self.client.get(self.url, data=request_params) self.assertEqual(response.status_code, 200) def test_event_view(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_monthly_view_no_sleep_logs(self): SleepLog.objects.filter(user=self.default_user).delete() response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_monthly_view_no_productivity_logs(self): DailyProductivityLog.objects.filter(user=self.default_user).delete() response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_monthly_view_no_supplement_logs(self): SupplementLog.objects.filter(user=self.default_user).delete() response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_monthly_view(self): request_params = { 'frequency': MONTHLY_FREQUENCY, } response = self.client.get(self.url, data=request_params) self.assertEqual(response.status_code, 200)
def test_submitter_state_with_required_permission_to_see(self): state = self.motion.state state.required_permission_to_see = 'permission_that_the_user_does_not_have_eiW8af9caizoh1thaece' state.save() user = get_user_model().objects.create_user( username='******', password='******') self.motion.submitters.add(user) submitter_client = APIClient() submitter_client.force_login(user) response = submitter_client.get(reverse('motion-detail', args=[self.motion.pk])) self.assertEqual(response.status_code, status.HTTP_200_OK)
class TestDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some agenda items are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config["general_system_enable_anonymous"] = True for index in range(10): Topic.objects.create(title="topic{}".format(index)) parent = Topic.objects.create(title="parent").agenda_item child = Topic.objects.create(title="child").agenda_item child.parent = parent child.save() Motion.objects.create(title="motion1") Motion.objects.create(title="motion2") Assignment.objects.create(title="assignment", open_posts=5) def test_admin(self): """ Tests that only the following db queries are done: * 5 requests to get the session an the request user with its permissions, * 2 requests to get the list of all agenda items, * 1 request to get all speakers, * 3 requests to get the assignments, motions and topics and * 2 requests for the motionsversions. TODO: There could be less requests to get the session and the request user. The last two request for the motionsversions are a bug. """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(13): self.client.get(reverse("item-list")) def test_anonymous(self): """ Tests that only the following db queries are done: * 2 requests to get the permission for anonymous (config and permissions) * 2 requests to get the list of all agenda items, * 1 request to get all speakers, * 3 requests to get the assignments, motions and topics and * 32 requests for the motionsversions. TODO: The last 32 requests are a bug. """ with self.assertNumQueries(40): self.client.get(reverse("item-list"))
def test_take_someone_else_number_not_verified(self): original_number = '+6171234567' UserPhoneNumberDetails.objects.create(user=self.test_user, phone_number=original_number) new_user = User.objects.create_user('new-user', 'testpassword') client = APIClient() client.force_login(new_user) details = { 'phone_number': original_number } response = client.post(self.url, data=details) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['phone_number'], original_number)
class TestMotionDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True for index in range(10): Motion.objects.create(title='motion{}'.format(index)) # TODO: Create some polls etc. def test_admin(self): """ Tests that only the following db queries are done: * 5 requests to get the session an the request user with its permissions, * 2 requests to get the list of all motions, * 1 request to get the motion versions, * 1 request to get the agenda item, * 1 request to get the motion log, * 1 request to get the polls, * 1 request to get the attachments, * 1 request to get the tags, * 2 requests to get the submitters and supporters """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(15): self.client.get(reverse('motion-list')) def test_anonymous(self): """ Tests that only the following db queries are done: * 2 requests to get the permission for anonymous (config and permissions) * 2 requests to get the list of all motions, * 1 request to get the motion versions, * 1 request to get the agenda item, * 1 request to get the motion log, * 1 request to get the polls, * 1 request to get the attachments, * 1 request to get the tags, * 2 requests to get the submitters and supporters * 10 requests for permissions. TODO: The last 10 requests are a bug. """ with self.assertNumQueries(22): self.client.get(reverse('motion-list'))
class BaseSupplementAnalyticsTests(TestCase): @classmethod def setUpAnalyticsData(cls): cls.default_user, _ = User.objects.get_or_create(username='******') builder = DemoHistoricalDataBuilder(cls.default_user) builder.create_historical_fixtures() supplement = Supplement.objects.filter(user=cls.default_user).first() cls.supplement = supplement def setUp(self): self.client = APIClient() self.client.force_login(self.default_user)
class TestRescueTimeAPIPostView(TestCase): @classmethod def setUpClass(cls): cls.url = reverse('rescuetime-user-update-productivity-history') super().setUpClass() def setUp(self): user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user = user self.client = APIClient() self.client.force_login(self.user) super().setUp() def test_view_with_no_details_should_error(self): response = self.client.post(self.url) # should say Missing some key, etc. etc self.assertTrue('Missing' in response.data) self.assertEqual(response.status_code, 400) def test_view_with_incorrect_details_types_should_error(self): """ IE. pass a non-date to a date field """ data = { 'rescuetime_api_key': 'cat', 'start_date': 'jungle', 'end_date': '2017-01-01' } response = self.client.post(self.url, data=data) self.assertTrue('start_date' in response.data) self.assertEqual(response.status_code, 400) def test_view_with_valid_parameters(self): """ Should just work. """ data = { 'rescuetime_api_key': 'cat', 'start_date': '2016-1-1', 'end_date': '2017-01-01' } response = self.client.post(self.url, data=data) self.assertEqual(response.status_code, 202) def test_view_with_invalid_start_and_end_date_greater(self): data = { 'rescuetime_api_key': 'cat', 'start_date': '2017-2-1', 'end_date': '2017-01-01' } response = self.client.post(self.url, data=data) self.assertEqual(response.status_code, 400)
class TestDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some assignments are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True for index in range(10): Assignment.objects.create(title='motion{}'.format(index), open_posts=1) @use_cache() def test_admin(self): """ Tests that only the following db queries are done: * 4 requests to get the session an the request user with its permissions, * 2 requests to get the list of all assignments, * 1 request to get all related users, * 1 request to get the agenda item, * 1 request to get the polls, * 1 request to get the tags and * 10 request to fetch each related user again. TODO: The last request are a bug. """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(20): self.client.get(reverse('assignment-list')) @use_cache() def test_anonymous(self): """ Tests that only the following db queries are done: * 3 requests to get the permission for anonymous, * 2 requests to get the list of all assignments, * 1 request to get all related users, * 1 request to get the agenda item, * 1 request to get the polls, * 1 request to get the tags and * 10 request to fetch each related user again. TODO: The last 10 requests are an bug. """ with self.assertNumQueries(19): self.client.get(reverse('assignment-list'))