def test_multi(self, link_handler, list_handler): url = resolve_url('django_opt_out_sparkpost:SparkPostUnsubscribeWebhook') test.Client().post(url, data=unsubscribe_multiple, content_type="application/json") self.assertTrue(link_handler.called) args, kwargs = link_handler.call_args self.assertEqual('*****@*****.**', kwargs['email']) self.assertTrue(list_handler.called) args, kwargs = list_handler.call_args self.assertEqual('*****@*****.**', kwargs['email'])
def setUp(self): super(BasicSessionCase, self).setUp() # Set up a session for this client because the session code in # Django's docs isn't working. engine = import_module(settings.SESSION_ENGINE) self.session = engine.SessionStore() self.session.save() session_key = self.session.session_key self.client = test.Client() self.client.cookies[settings.SESSION_COOKIE_NAME] = session_key
def setUpTestData(cls): cls.client = test.Client() cls.user = auth_factories.UserFactory() cls.term = factories.TermFactory(value='fake term') cls.definition = factories.DefinitionFactory( uuid='6b4a7a9f-3b8f-494b-8565-f960065802ba', term=cls.term, value='fake definition', user=cls.user, ) cls.url = cls.definition.get_absolute_url()
def test_jsi18n_caching(self): # The jsi18n catalog should be cached for a long time. # Get the url from a real page so it includes the build id. client = test.Client() doc = pq(client.get('/', follow=True).content) js_url = reverse('jsi18n') url_with_build = doc('script[src^="%s"]' % js_url).attr('src') response = client.get(url_with_build, follow=True) self.assertCloseToNow(response['Expires'], now=datetime.now() + timedelta(days=7))
def test_remote_addr(self, set_remote_addr_mock): """Make sure we're setting REMOTE_ADDR from X_FORWARDED_FOR.""" client = test.Client() # Send X-Forwarded-For as it shows up in a wsgi request. client.get('/en-US/developers/', follow=True, HTTP_X_FORWARDED_FOR='1.1.1.1', REMOTE_ADDR='127.0.0.1') assert set_remote_addr_mock.call_count == 2 assert set_remote_addr_mock.call_args_list[0] == (('1.1.1.1', ), {}) assert set_remote_addr_mock.call_args_list[1] == ((None, ), {})
def setUp(self): self.client = test.Client(enforce_csrf_checks=False) self.response = None startdate = datetime.strptime('2017-02-04', '%Y-%m-%d') enddate = datetime.strptime('2019-10-01', '%Y-%m-%d') self.program = ProgramFactory(reporting_period_start=startdate, reporting_period_end=enddate) self.request_params = { 'csrfmiddlewaretoken': 'asdf', 'program': self.program.id }
def test_user_registration_valid(self): c = test.Client() response = c.post('/signup/', { 'email': self.email, 'password': self.password }) body = response.json() if 'redirect' in body: self.assertEqual(body['redirect'], '/confirm_email') else: self.assertTrue(False)
def setUp(self): self.client = test.Client() self.user = auth_factories.UserFactory() self.term = factories.TermFactory(value='fake term') self.definition = factories.DefinitionFactory( uuid='6b4a7a9f-3b8f-494b-8565-f960065802ba', term=self.term, value='fake definition', user=self.user, ) self.url = self.definition.get_absolute_url()
def test_lbheartbeat_middleware(self): # /__lbheartbeat__ should be return a 200 from middleware, bypassing later # middleware and view code. with self.assertNumQueries(0): response = test.Client().get('/__lbheartbeat__', SERVER_NAME='elb-internal') assert response.status_code == 200 assert response.content == b'' assert response['Cache-Control'] == ( 'max-age=0, no-cache, no-store, must-revalidate, private' )
def test_trailing_slash_middleware(): response = test.Client().get(u'/en-US/about/?xxx=\xc3') assert response.status_code == 301 # Django's behaviour for URLs containing unicode characters is different # under Python 2 and 3. This is fine though, as browsers should send URLs # urlencoded, and that's tested above in test_redirect_with_unicode_get(). # We just need to make sure we're not crashing on such URLs. if six.PY2: assert response['Location'].endswith('/en-US/about?xxx=%C3%83') else: assert response['Location'].endswith('/en-US/about?xxx=%C3%83%C2%83')
def setUp(self): self.mask_url = reverse('disguise_mask') self.unmask_url = reverse('disguise_unmask') self.root = User.objects.create_superuser(username='******', password='******', email='*****@*****.**') self.user = User.objects.create_user(username='******', password='******', email='*****@*****.**') self.client = test.Client() self.client.login(username='******', password='******')
def fn1(): url = shortcuts.reverse('accounts:sign-up') data = { 'username': '******', 'password1': 'BananaGrapevine99', 'password2': 'BananaGrapevine99' } client = test.Client() response = client.post(url, data) print(response.context['form'])
def test_user_registration_invalid(self): c = test.Client() self.__insert_user() response = c.post('/signup/', { 'email': self.email, 'password': self.password }) body = response.json() if 'error' in body.keys(): self.assertEqual(body['error'], 'Account already exists') else: self.assertTrue(False)
def create(self): self.last_test_settings = settings.TESTING settings.TESTING = True test.utils.setup_test_environment() self.old_config = test.utils.setup_databases( TEST_SETUP_VERBOSITY, False, ) self.client = test.Client() self.client.get('/') self.created = True
def test_button_caching(self): """The button popups should be cached for a long time.""" # Get the url from a real page so it includes the build id. client = test.Client() doc = pq(client.get('/', follow=True).content) js_url = absolutify(reverse('addons.buttons.js')) url_with_build = doc('script[src^="%s"]' % js_url).attr('src') response = client.get(url_with_build, follow=True) fmt = '%a, %d %b %Y %H:%M:%S GMT' expires = datetime.strptime(response['Expires'], fmt) assert (expires - datetime.now()).days >= 365
def test_polls_list(self): c = test.Client() time_in_semester = self.semester.semester_beginning + ( self.semester.semester_ending - self.semester.semester_beginning) / 2 with freeze_time(time_in_semester): c.force_login(self.student.user) polls = Poll.get_all_polls_for_student(self.student) keys = RSAKeys.objects.filter(poll__in=polls) self.assertEqual(len(keys), len(polls)) r = c.get('/grade/ticket/get-poll-data') self.assertEqual(len(r.json()), len(polls))
def test_jsi18n_caching(self): # The jsi18n catalog should be cached for a long time. # Get the url from a real page so it includes the build id. client = test.Client() doc = pq(client.get('/', follow=True).content) js_url = reverse('jsi18n') url_with_build = doc('script[src^="%s"]' % js_url).attr('src') response = client.get(url_with_build, follow=True) fmt = '%a, %d %b %Y %H:%M:%S GMT' expires = datetime.strptime(response['Expires'], fmt) assert (expires - datetime.now()).days >= 365
def setUp(self): self.denunciable = Denunciable.objects.create( denunciable_id=1, denunciable_type='type' ) self.denunciation = Denunciation.objects.create( justification='justification_1', denunciable=self.denunciable ) self.denunciation_url = self._get_detail_url(self.denunciation.pk) self.client = test.Client()
def setUp(self): super().setUp() # define an email_client who will login via email self.email_client_username = "******" self.email_client_email = "*****@*****.**" self.email_client_password = "******" self.email_client = User.objects.create_user( username=self.email_client_username, email=self.email_client_email, password=self.email_client_password, ) self.email_client = test.Client()
def setup_client(self, user_proposals: List[str] = []): """ setup test HTTP client which is logged in with a user 'dummy' that have access to PROP1 and PROP2 proposals """ self.user = auth.ISPyBBackend()._get_user_obj("dummy") self.client = test.Client() self.client.force_login(user=self.user) session = self.client.session session["proposals"] = user_proposals session.save()
def setUpClass(cls): cls.username = '******' cls.password = '******' cls.user = models.User(username=cls.username, email='*****@*****.**') cls.user.set_password(cls.password) cls.user.save() cls.user_profile = models.UserProfile.objects.get(user=cls.user) cls.uuid = "59216199-d664-4b7a-a2db-6f26e9a5d208" # Create a test client. cls.client = test.Client()
def test_anon_access_generated_notpublic(self): plan = Plan.objects.create( template=self.template, title='test plan', added_by=self.user, modified_by=self.user, ) c = test.Client() kwargs = {'plan': plan.pk} response = c.get(reverse(self.urlname, kwargs=kwargs)) self.assertEqual(response.status_code, 404, '{} should be hidden'.format(self.urlname))
def test_source_with_wrong_unicode_get(): # The following url is a string (bytes), not unicode. response = test.Client().get('/firefox/collections/mozmj/autumn/' '?source=firefoxsocialmedia\x14\x85') assert response.status_code == 302 # Django's behaviour for URLs containing unicode characters is different # under Python 2 and 3. This is fine though, as browsers should send URLs # urlencoded, and that's tested above in test_redirect_with_unicode_get(). # We just need to make sure we're not crashing on such URLs. if six.PY2: assert response['Location'].endswith('?source=firefoxsocialmedia%14') else: assert response['Location'].endswith( '?source=firefoxsocialmedia%14%C3%82%C2%85')
def test_fake_fxa_authorization_correct_values_passed(): with override_settings(DEBUG=True): # USE_FAKE_FXA_AUTH is already True url = reverse('fake-fxa-authorization') response = test.Client().get(url, {'state': 'foobar'}) assert response.status_code == 200 doc = pq(response.content) form = doc('#fake_fxa_authorization')[0] assert form.attrib['action'] == reverse('auth:accounts.authenticate') elm = doc('#fake_fxa_authorization input[name=code]')[0] assert elm.attrib['value'] == 'fakecode' elm = doc('#fake_fxa_authorization input[name=state]')[0] assert elm.attrib['value'] == 'foobar' elm = doc('#fake_fxa_authorization input[name=fake_fxa_email]') assert elm # No value yet, should just be present.
def test_feedback_based_on_saved_tags(self): feedback = factories.OptOutFeedbackFactory.create_batch(3) tag1 = factories.OptOutTagFactory() feedback.extend(factories.OptOutFeedbackFactory.create_batch(3, tags=(tag1,))) tag2 = factories.OptOutTagFactory() factories.OptOutFeedbackFactory.create_batch(3, tags=(tag2,)) item = factories.OptOutFactory() item.tags.create(tag=tag1) url = resolve_url("django_opt_out:OptOutUpdate", item.pk, item.secret, item.email) response = test.Client().get(url) self.assertEqual(200, response.status_code) self.assertNoFormErrors(response) choices = [pk for pk, label in response.context_data['form'].fields['feedback'].choices] self.assertEqual(set((f.pk for f in feedback)), set(choices))
def test_feedback_based_on_tags(self): feedback = factories.OptOutFeedbackFactory.create_batch(3) tag1 = factories.OptOutTagFactory() feedback.extend(factories.OptOutFeedbackFactory.create_batch(3, tags=(tag1,))) tag2 = factories.OptOutTagFactory() factories.OptOutFeedbackFactory.create_batch(3, tags=(tag2,)) tag3 = factories.OptOutTagFactory() feedback.extend(factories.OptOutFeedbackFactory.create_batch(3, tags=(tag3,))) url = get_opt_out_path("*****@*****.**", tag1.name, tag3.name) response = test.Client().get(url) self.assertEqual(200, response.status_code) self.assertEqual({}, response.context_data['form'].errors) choices = [pk for pk, label in response.context_data['form'].fields['feedback'].choices] self.assertEqual(set((f.pk for f in feedback)), set(choices))
def test_plugincheck_redirect(self): r = test.Client().get('/services/pfs.php?' 'mimetype=application%2Fx-shockwave-flash&' 'appID={ec8030f7-c20a-464f-9b0e-13a3a9e97384}&' 'appVersion=20120215223356&' 'clientOS=Windows%20NT%205.1&' 'chromeLocale=en-US&appRelease=10.0.2') self.assertEquals(r.status_code, 302) self.assertEquals(r['Location'], ('https://pfs.mozilla.org/pfs.py?' 'mimetype=application%2Fx-shockwave-flash&' 'appID=%7Bec8030f7-c20a-464f-9b0e-13a3a9e97384%7D&' 'appVersion=20120215223356&' 'clientOS=Windows%20NT%205.1&' 'chromeLocale=en-US&appRelease=10.0.2'))
def setUp(self): self.root_category = models.Category.objects.get(id=1) self.second_category = models.Category.objects.get(id=2) self.third_category = models.Category.objects.get(id=3) self.another_category = models.Category.objects.get(id=4) self.post1 = models.Post.objects.get(id=1) self.post2 = models.Post.objects.get(id=2) self.post3 = models.Post.objects.get(id=3) self.post4 = models.Post.objects.get(id=4) self.user = auth.models.User.objects.get(id=1) self.client = test.Client()
def setUpTestData(cls): cls.client = test.Client() cls.term = factories.TermFactory(value='fake term') cls.definition_foo = factories.DefinitionFactory( uuid='cb8d30f8-b60a-46e8-9cad-f3d5ff28d269', term=cls.term, value='foo', ) cls.definition_bar = factories.DefinitionFactory( uuid='75484634-4f96-4bc9-8d94-bfe8523ba7cd', term=cls.term, value='bar', ) cls.url = reverse('term-detail', kwargs={'slug': cls.term.slug})
def setUp(self): self.client = test.Client() self.voter = self._create_member('*****@*****.**', 'My Voter', False) self.voter2 = self._create_member('*****@*****.**', 'My Voter 2', False) self.voter3 = self._create_member('*****@*****.**', 'My Voter 3', False) self.candidate = self._create_member('*****@*****.**', 'Candidate', True, 'lon') self.candidate2 = self._create_member('*****@*****.**', 'Candidate', True, 'lon') self.candidate3 = self._create_member('*****@*****.**', 'Candidate', True, 'mide') self.category1 = Category.objects.create(number=1, title='Category 1') self.category2 = Category.objects.create(number=2, title='Category 2')