Пример #1
0
class TestAssignmentUploadForm(TestCase):
    def upload_test(self):
        self.client = Client()
        self.username = 'vba'
        self.email = 'test@test.com'
        self.password = 'test'
        self.test_user = User.objects.create_user(self.username, self.email, self.password)
        login = self.client.login(username=self.username, password=self.password)
        self.assertEqual(login, True)
        course = Course.objects.create(number='1234', name='Test course')
        student = Student.objects.create(
            user=User.objects.create_user('test_user', first_name='Student'),
            course=course,
        )
        staff = Staff.objects.create(
            user=User.objects.create_user('test_staff', first_name='Staff')
        )
        subject = Subject.objects.create(course=course, name='Subject1', staff=staff)
        assignment = Assignment.objects.create(subject=subject, topic='This is Enemy', deadline=timezone.now(),
                                               description="I need holiday..")
        with open('requirements.txt') as fp:
            self.client.post('/assignments/' + assignment.pk + '/upload/',
                             {'assignment': assignment, 'user': student.user, 'created': timezone.now(), 'file': fp})
        response = self.client.get(reverse('assignment_detail', args=(assignment.pk,)))
        print(response.status_code)
        self.assertContains(response, assignment.topic)
        self.assertContains(response, 'requirements.txt')
        self.assertEqual(response.status_code, 200)
Пример #2
0
    def test_activate(self):
        c = Client()

        response = c.get('/signup/activate/')
        self.assertEqual(response.status_code, 200)

        response = c.post('/signup/activate/', {'ps1_email': 'J.R.Hacker@example.com'}, follow=True)
        self.assertEqual(response.status_code, 200)

        # "read" email
        token = self.get_token()
        activation_url = '/signup/activate/confirm/{}'.format(token.token)
        response = c.get(activation_url)
        self.assertEqual(response.status_code, 200)
        
        post_data = {
            'preferred_username': 'jay',
            'first_name': 'Jay',
            'last_name': 'Hacker',
            'preferred_email': 'J.R.Hacker@example.com',
            'token': token.token,
        }
        response = c.post(activation_url, post_data, follow=True)
        self.assertEqual(response.status_code, 200)

        jay = Person.objects.get(pk=self.person.pk)
        self.assertIsNotNone(jay.user)
        PS1User.objects.delete_user(jay.user)
Пример #3
0
 def test_post_user_check_result_false(self):
     client = Client()
     client.post(
         '/users_check/', {'id_user_1': 123, 'id_user_2': 3}
     )
     self.assertEqual('res' in client._session().keys(), True)
     self.assertEqual(False in client._session().values(), True)
Пример #4
0
    def test_upload(self):
        """Can we create an image on the filestore?"""
        username, user = _make_user()
        c = Client()

        with open(UPLOAD_FILE) as photo_fd:
            response = c.post("/umedia/", {
                    "title": "a picture of me I just took",
                    "photo": photo_fd
                    })
            self.assertEquals(302, response.status_code)
            parsed = urlparse.urlparse(response["Location"])
            self.assertEquals(parsed.path, settings.LOGIN_URL)

        # Now login
        loggedin = c.login(username=username, password="secret")
        self.assertTrue(loggedin)
        with open(UPLOAD_FILE) as photo_fd:
            response = c.post("/umedia/", {
                    "title": "a picture of me I just took",
                    "photo": photo_fd
                    })
            self.assertEquals(201, response.status_code)

            # What's the url
            parsed = urlparse.urlparse(response["Location"])

            # Check we've got the correct file type
            self.assertEquals(os.path.splitext(parsed.path)[1][1:], "jpg")
            
            # Check that is starts with something under the MEDIA_DOMAIN
            self.assertEquals(
                settings.MEDIA_DOMAIN, 
                ".".join(parsed.netloc.split(".")[2:])
                )
class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.authentication'

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = 'john'
        self.email = 'lennon@thebeatles.com'
        self.password = 'password'
        self.user = User.objects.create_user(self.username, self.email, self.password)

    def test_post_form_passing_basic_auth(self):
        """Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF"""
        auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
        response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, 200)

    def test_post_json_passing_basic_auth(self):
        """Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF"""
        auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
        response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, 200)

    def test_post_form_failing_basic_auth(self):
        """Ensure POSTing form over basic auth without correct credentials fails"""
        response = self.csrf_client.post('/basic/', {'example': 'example'})
        self.assertEqual(response.status_code, 401)

    def test_post_json_failing_basic_auth(self):
        """Ensure POSTing json over basic auth without correct credentials fails"""
        response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json')
        self.assertEqual(response.status_code, 401)
        self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"')
Пример #6
0
class EditProfileTestCase(TestCase):
    def setUp(self):
        self.my_user = User.objects.get(id=3)
        self.client = Client()

    def tearDown(self):
        self.my_user = None
        self.client = None

    def sign_in_first(self):
        return self.client.login(username=self.my_user.username, password="xx")

    def test_user_redirected_to_profile_if_email_valid(self):
        self.sign_in_first()
        resp = self.client.post("/editprofile/", {'email': 'ski@test.fi'})
        self.assertEqual(User.objects.get(id=3).email, 'ski@test.fi')
        self.assertRedirects(resp, '/profile/')

    def test_error_redirected_to_edit_if_email_invalid(self):
        self.sign_in_first()
        resp = self.client.post("/editprofile/", {'email': 'skitest.fi'})
        self.assertNotEqual(User.objects.get(id=3).email, 'skitest.fi')
        self.assertFormError(resp, 'form', 'email', "Enter a valid email address.")
        self.assertTemplateUsed(resp, 'editprofile.html')

    def test_form_sent_in_response_to_get_request(self):
        self.sign_in_first()
        resp = self.client.post("/editprofile/")
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed("editprofile.html")
Пример #7
0
class TestContentParsingWithAuthentication(TestCase):
    urls = "djangorestframework.tests.content"

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = "john"
        self.email = "lennon@thebeatles.com"
        self.password = "password"
        self.user = User.objects.create_user(self.username, self.email, self.password)
        self.req = RequestFactory()

    def test_user_logged_in_authentication_has_post_when_not_logged_in(self):
        """Ensures request.POST exists after UserLoggedInAuthentication when user doesn't log in"""
        content = {"example": "example"}

        response = self.client.post("/", content)
        self.assertEqual(status.OK, response.status_code, "POST data is malformed")

        response = self.csrf_client.post("/", content)
        self.assertEqual(status.OK, response.status_code, "POST data is malformed")

    def test_user_logged_in_authentication_has_post_when_logged_in(self):
        """Ensures request.POST exists after UserLoggedInAuthentication when user does log in"""
        self.client.login(username="john", password="password")
        self.csrf_client.login(username="john", password="password")
        content = {"example": "example"}

        response = self.client.post("/", content)
        self.assertEqual(status.OK, response.status_code, "POST data is malformed")

        response = self.csrf_client.post("/", content)
        self.assertEqual(status.OK, response.status_code, "POST data is malformed")
Пример #8
0
class TestGeneTable(TestCase):
    def setUp(self):
        args = []
        opts = {'dumpfile': 'test_db_dump.xml', 'verbosity': 0}
        cmd = 'migrate_db'
        call_command(cmd, *args, **opts)
        self.client = Client()

    def test_view_index(self):
        response = self.client.get('/create_gene_table/')
        self.assertEqual(200, response.status_code)

    def test_results(self):
        expected = 'COI,mitochondrial,1047,58.357,42.0,0.0,58.0,17.299999999999997,22.5,9.5,9.1'
        response = self.client.post('/create_gene_table/results/',
                                    {
                                        'taxonset': 1,
                                        'geneset': 1,
                                        'translations': False,
                                    })
        self.assertTrue(expected in str(response.content))

    def test_results_invalid_form(self):
        response = self.client.post('/create_gene_table/results/', {
            'taxonset': 1000,
            'geneset': 1000,
            'translations': False,
        })
        expected = 'Erebia'
        self.assertTrue(expected in str(response.content))
Пример #9
0
    def test_registration_api_fails_if_user_exists(self):
        c = Client()
        response = c.post('/register/', {'username': 'john123',
                                         'password': 'smith123',
                                         'email': 'smith@asdf.com',
                                         'first_name':'John',
                                         'last_name':'smith',
                                         'security_question':'mother maiden name',
                                         'security_answer':'andrews',
                                         'gender':'male',
                                         'phone_number':'1231231233'})
        second_response = c.post('/register/', {'username': 'john123',
                                         'password': 'smith123',
                                         'email': 'smith@asdf.com',
                                         'first_name':'John',
                                         'last_name':'smith',
                                         'security_question':'mother maiden name',
                                         'security_answer':'andrews',
                                         'gender':'male',
                                         'phone_number':'1231231233'})

        
        self.assertEqual(second_response.status_code, 400)
        saved_user = ITUUser.objects.filter(username='smith@asdf.com')
        # still should only have one
        self.assertEqual(len(saved_user), 1)
class QuestionMethodTests(TestCase):
    def setUp(self):
        first_name = "Joe"
        second_name = "Man"
        email = "joe@asu.edu"
        password = "password"

        self.user = User(first_name=first_name, second_name=second_name, email=email, password=password)
        self.user.save()
        Picture(user=self.user, photo="First_photo.png").save()
        Picture(user=self.user, photo="Second_photo.png").save()

        Settings(user=self.user, profile_pic="Profile_photo.png").save()

        self.client = Client()
        self.client.post("/login", data={"email": self.user.email, "password": self.user.password})

    def test_logout_leads_to_login_page(self):
        # setup
        response = self.client.get("/logout")

        # Test
        self.assertEqual(response.status_code, 302)
        self.assertRegexpMatches(response.url, "login")

    def test_logout_link_is_available_at_home(self):
        # setup
        response = self.client.get("/home")

        # Test
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, '<a href="/logout" class="">Logout</a>')
    def test_edit_site(self):
        c = Client()
        val = c.login(username = "frank",password = "password")

        print 'the login value is: %s' % val

        data= {'site_name':u'kibuye',
               'comission_date':datetime(2015,12,11,22,0),
               'location_city':u'kigali',
               'location_country':u'rwanda',
               'time_zone':'Africa/Kigali',
               'position_0':36,
               'position_1':42,
               'installed_kw':2,
               'system_voltage':4,
               'number_of_panels':100,
               'site_Id':2,
               'battery_bank_capacity':1200,
               'api_key': 'testing',
               'api_key_numeric': '123456'}

        response = c.post('/edit_site/' + str(self.site.id) , data)

        # Testing if the site has been edited succesfully
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Sesh_Site.objects.first().site_name, 'kibuye')


        # Checking for another unauthorized user
        val = c.login(username="test_user",password="test.test.test")
        response = c.post('/edit_site/' + str(self.site.id), data)
        self.assertEqual(response.status_code, 403)
Пример #12
0
class TestClient(unittest.TestCase):
    def setUp(self):
        # Every test needs a client.
        self.client = Client()
        g = Gmina.objects.create(nazwa="Jakas")
        self.o = Obwod.objects.create(adres="Blabla", gmina=g)


    def test_getting_obwod(self):
        response = self.client.post('/obwod/', {'obw_id': self.o.id})

        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(self.o.toDict(), data)

    def test_saving_obwod(self):
        response = self.client.post('/save/', {'obw_id': self.o.id, 'ileKart': '3', 'upr': '4', 'wer': '0'})

        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)

        self.assertEqual(1, data['dict']['wer'])
        self.assertEqual('3', data['dict']['ile'])
        self.assertEqual('4', data['dict']['upr'])
        self.assertEqual(self.o.id, data['dict']['id'])
        self.assertEqual('Blabla', data['dict']['adres'])
        self.assertEqual(False, data['err'])
Пример #13
0
class ViewTest(TestCase):
  def setUp(self):
      self.client_stub = Client()
      self.person = Person(first_name = 'TestFirst',last_name = 'TestLast')
      self.person.save()
      self.phone = Phone(person = self.person,number = '7778889999')
      self.phone.save()
  def test_view_home_route(self):
      response = self.client_stub.get('/')
      self.assertEquals(response.status_code, 200)
  def test_view_contacts_route(self):
      response = self.client_stub.get('/all/')
      self.assertEquals(response.status_code, 200)
  def test_add_contact_route(self):
      response = self.client_stub.get('/add/')
      self.assertEqual(response.status_code, 200)
  def test_create_contact_successful_route(self):
      response = self.client_stub.post('/create',data = {'first_name' : 'testFirst', 'last_name':'tester', 'email':'test@tester.com', 'address':'1234 nowhere', 'city':'far away', 'state':'CO', 'country':'USA', 'number':'987654321'})
      self.assertEqual(response.status_code, 302)
  def test_create_contact_unsuccessful_route(self):
      response = self.client_stub.post('/create',data = {'first_name' : 'tester_first_n@me', 'last_name':'test', 'email':'tester@test.com', 'address':'5678 everywhere', 'city':'far from here', 'state':'CA', 'country':'USA', 'number':'987654321'})
      self.assertEqual(response.status_code, 200)
  def tearDown(self):
      self.phone.delete()
      self.person.delete()  
Пример #14
0
    def test_session_auth_post_requires_csrf_token(self):
        """ Verify non-GET requests require a CSRF token be attached to the request. """
        user = UserFactory(password=self.password, is_staff=True)
        client = Client(enforce_csrf_checks=True)
        self.assertTrue(client.login(username=user.username, password=self.password))

        data = {
            'course_key': 'a/b/c',
            'enabled': True
        }

        # POSTs without a CSRF token should fail.
        response = client.post(self.path, data=json.dumps(data), content_type=JSON)

        # NOTE (CCB): Ordinarily we would expect a 403; however, since the CSRF validation and session authentication
        # fail, DRF considers the request to be unauthenticated.
        self.assertEqual(response.status_code, 401)
        self.assertIn('CSRF', response.content)

        # Retrieve a CSRF token
        response = client.get('/dashboard')
        csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value  # pylint: disable=no-member
        self.assertGreater(len(csrf_token), 0)

        # Ensure POSTs made with the token succeed.
        response = client.post(self.path, data=json.dumps(data), content_type=JSON, HTTP_X_CSRFTOKEN=csrf_token)
        self.assertEqual(response.status_code, 201)
Пример #15
0
class MontlyEventViewTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = PyDayUser.objects._create_user("bla@bla.bla", "secret",
                                                   "MynameisWhat",
                                                   "MynameisWho")

    def test_get_not_logged(self):
        response = self.client.get(reverse("pyday_calendar:monthly_events"),
                                   follow=True)
        self.assertEqual(response.redirect_chain,
                         [('/social/register/?next=/calendar/monthly_events/', 302)])

    def test_get_logged(self):
        self.client.login(email='bla@bla.bla', password='secret')
        with self.assertTemplateUsed("monthly_event.html"):
            resp = self.client.get(reverse("pyday_calendar:monthly_events"))
            self.assertEqual(resp.status_code, 200)

    def test_post_wrong_date(self):
        self.client.login(email='bla@bla.bla', password='secret')
        with self.assertTemplateUsed("error.html"):
            self.client.post(reverse("pyday_calendar:monthly_events"), {
                             "date": "60/2016"})

    def test_post_right_date(self):
        self.client.login(email='bla@bla.bla', password='secret')
        with self.assertTemplateUsed("monthly_event.html"):
            self.client.post(reverse("pyday_calendar:monthly_events"), {
                             "date": "6/2016"})
Пример #16
0
class RegisterUser(TestCase):
    """Test for 200 OK at '/'"""

    def setUp(self):
        self.client = Client()
        self.username = fake.user_name()
        self.password = fake.password()
        self.email = fake.email()

    def test_register_user(self):
        response = self.client.post(
            "/register/",
            {"username": self.username, "password1": self.password, "password2": self.password, "email": self.email},
            follow=True,
        )
        self.assertEqual(response.status_code, 200)
        self.assertIn("activate", response.content)

    def test_activate(self):
        register = self.client.post(
            "/register/",
            {"username": self.username, "password1": self.password, "password2": self.password, "email": self.email},
            follow=True,
        )
        # Regex lifted from:
        # http://stackoverflow.com/questions/9760588/how-do-you-extract-a-url-from-a-string-using-python
        link = re.search("(?P<url>https?://[^\s]+)", mail.outbox[0].body).group("url")
        link_bits = link.split("/")
        rel_uri = "/" + "/".join(link_bits[3:])
        activate = self.client.get(rel_uri, follow=True)
        self.assertIn("activate/complete", activate.wsgi_request.path)
        # Newly registered user now attempts to login
        logginin = self.client.post("/login/", {"username": self.username, "password": self.password}, follow=True)
        self.assertIn(self.username, logginin.content)
Пример #17
0
class ChangePasswordTestCase(TestCase):
    def setUp(self):
        self.my_user = User.objects.get(id=3)
        self.client = Client()

    def tearDown(self):
        self.my_user = None
        self.client = None

    def sign_in_first(self):
        return self.client.login(username=self.my_user.username, password="xx")

    def test_user_should_login_first(self):
        # 'old_password', 'new_password1', 'new_password2'
        resp = self.client.post('/changepassword/', {'old_password': 'xx',
                                                     'new_password1': 'test',
                                                     'new_password2': 'test'})
        self.assertEqual(resp.status_code, 302, "The user is redirected because he is not logged in")
        self.assertRedirects(resp, "/signin/?next=/changepassword/")

    def test_if_password_changed_user_redirected_to_profile(self):
        self.sign_in_first()
        resp = self.client.post('/changepassword/', {'old_password': 'xx',
                                                     'new_password1': 'test',
                                                     'new_password2': 'test'})
        login_successful = self.client.login(username=self.my_user.username, password="test")
        self.assertTrue(login_successful)
        self.assertEqual(resp.status_code, 302)
        self.assertRedirects(resp, '/profile/')

    def test_password_form_sent_through_get_method(self):
        self.sign_in_first()
        resp = self.client.get('/changepassword/')
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed("changepassword.html")
Пример #18
0
class PasswordResetChangeTest(ShadowConTestCase):
    def setUp(self):
        self.client = Client()

    def run_test(self, key):
        response = self.client.get(reverse(key))
        self.assertSectionContains(response, "ShadowCon 2016", "title")
        return response

    def test_login(self):
        response = self.run_test('login')
        self.assertSectionContains(response, '<p><a href="%s">%s</a></p>' % (reverse('password_reset'),
                                                                             'Lost password\\?'),
                                   'section id="main" role="main"', '/section')
        self.assertSectionContains(response, '<p><a href="%s">%s</a></p>' % (reverse('convention:new_user'),
                                                                             'Create New Account'),
                                   'section id="main" role="main"', '/section')

    def test_logout(self):
        response = self.run_test('logout')
        self.assertSectionContains(response, 'You have successfully logged out',
                                   'section id="main" role="main"', '/section')

    def test_password_change(self):
        self.client.login(username="user", password="123")
        response = self.run_test('password_change')
        self.assertSectionContains(response, 'Enter new password', 'section id="main" role="main"', '/section')

    def test_password_change_done(self):
        self.client.login(username="user", password="123")
        response = self.run_test('password_change_done')
        self.assertSectionContains(response, '<h2>Password Changed</h2>', 'section id="main" role="main"', '/section')

    def test_password_reset(self):
        response = self.run_test('password_reset')
        self.assertSectionContains(response, 'Forgotten your password\\? Enter your',
                                   'section id="main" role="main"', '/section')

    def test_password_reset_done(self):
        response = self.run_test('password_reset_done')
        self.assertSectionContains(response, 'Password reset sent', 'section id="main" role="main"', '/section')

    def test_password_reset_confirm_invalid_link(self):
        response = self.client.get(reverse('password_reset_confirm', args=["invalid", "4a8-cd1bf13135ee4cae7176"]))
        self.assertSectionContains(response, "ShadowCon 2016", "title")
        self.assertSectionContains(response, 'The password reset link was invalid',
                                   'section id="main" role="main"', '/section')

    def test_password_reset_confirm_valid_link(self):
        self.client.post(reverse('password_reset'), {"email": "user-test@mg.shadowcon.net"})

        email = self.get_email()
        start = str(email.body).index('/reset')
        stop = str(email.body).index('Your username, in case you\'ve forgotten: user')
        link = str(email.body)[start:stop].strip()

        response = self.client.get(link)
        self.assertSectionContains(response, "ShadowCon 2016", "title")
        self.assertSectionContains(response, 'Please enter your new password twice',
                                   'section id="main" role="main"', '/section')
Пример #19
0
class AlarmViewTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = PyDayUser.objects._create_user("bla@bla.bla", "secret",
                                                   "MynameisWhat",
                                                   "MynameisWho")
        self.client.login(email='bla@bla.bla', password='secret')

    def test_get(self):
        with self.assertTemplateUsed("create_alarm.html"):
            self.client.get(reverse("pyday_alarms:alarms"))

    def test_post(self):
        with self.assertTemplateUsed("error.html"):
            response = self.client.post(reverse("pyday_alarms:alarms"),
                                        {'date': '07/01/2016', 'hour': '1',
                                         'mins': '0', 'message': 'haha'},
                                        follow=True)
            self.assertContains(response, "Raspberry!")

    def test_post_invalid_form(self):
        with self.assertTemplateUsed("error.html"):
            response = self.client.post(reverse("pyday_alarms:alarms"), {})
            self.assertContains(response, "Invalid form")
Пример #20
0
class ArticleTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.factory = RequestFactory()

    def test_validate_article_edition(self):
        user2 = User.objects.create_user(username="teste12345",
                                         email="reallynice2@gmail.com",
                                         password="supersecret123")

        article = Article()
        article.title = "nicetitle"
        article.content = "nicecontent"
        article.create_user = user2
        article.create_user.id = user2.id
        article.save()
        self.client.login(username="teste1234", password="supersecret123")
        response = self.client.get(reverse('edit_article', kwargs={'id': '1'}))
        self.assertEqual(response.status_code, 302)
        response = self.client.post(reverse('edit_article',
                                            kwargs={'id': '1'}))
        self.assertEqual(response.status_code, 302)
        self.client.login(username="teste12345", password="supersecret123")
        response = self.client.get(reverse('edit_article', kwargs={'id': '1'}),
                                   user=user2)
        self.assertEqual(response.status_code, 200)
        response = self.client.post(reverse('edit_article',
                                            kwargs={'id': '1'}))
        self.assertEqual(response.status_code, 200)
Пример #21
0
class TestUpdateUserPerms(TransactionTestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(username='hodor', password='hodor',
                                             first_name='Hodor', last_name='HodorHodor',
                                             email='hodor@hodor.hodor')
        Perms.objects.create(user=self.user, access_level=1).save()

    def test_update_user_perms(self):
        """Updating user permissions"""
        self.client.login(username='hodor', password='hodor')
        new_user = User.objects.create_user(username='phil', password='pjfry',
                                            first_name='Phillip', last_name='J Fry',
                                            email='phil.fry@planetexpress.com')

        #Test if perms are created for new user
        response = self.client.post('/users/perms/update/', data={'user_id': new_user.id, 'access_level': '5'}, follow=True)
        self.assertRedirects(response, '/users/view/%d/' % new_user.id)
        user = User.objects.get(pk=new_user.id)
        self.assertEquals(user.perms.access_level, 5)

        # Test updating once you have perms
        response = self.client.post('/users/perms/update/', data={'user_id': new_user.id, 'access_level': '2'}, follow=True)
        self.assertRedirects(response, '/users/view/%d/' % new_user.id)
        user = User.objects.get(pk=new_user.id)
        self.assertEquals(user.perms.access_level, 2)
Пример #22
0
    def test_edit_item(self):
        timestamp = datetime.now()
        description = 'Coke'
        caffeine = 50
        c = Client()
        c.login(username='test', password='password')
        response = c.post('/record/item', {
            'time': self.timestamp,
            'description': self.description,
            'caffeine': self.caffeine,
        })

        response = c.post('/edit/item?id=1', {
            'time': timestamp,
            'description': description,
            'caffeine': caffeine,
        })
        self.assertEqual(response.status_code, 303)
        record = Record.objects.get(pk=1)
        self.assertEqual(record.time, timestamp)
        self.assertEqual(record.caffeine, caffeine)
        self.assertEqual(record.description, description)

        response = c.post('/edit/item?id=2', {
            'time': timestamp,
            'description': description,
            'caffeine': caffeine,
        })
        self.assertEqual(response.status_code, 404)
Пример #23
0
class LoginTest(SimpleTestCase):
    user = 'logintest'
    pwd = '123456'

    def setUp(self):
        self.client = Client()
        if not User.objects.filter(username=self.user).first():
            User.objects.create_user(username=self.user, password=self.pwd)

    def test_200ok(self):
        self.assertEqual(self.client.get('/login/').status_code, 200)
        self.assertEqual(self.client.post('/login/').status_code, 200)

    def test_login_normal(self):
        self.assertTrue(self.client.login(username=self.user, password=self.pwd))

        self.client.logout()
        res = self.client.post(path='/login/', data={'username': self.user, 'password': self.pwd})
        self.assertEqual(res.url, 'http://testserver/index.html')

    def test_login_nextpage(self):
        res = self.client.post(path='/login/', data={'username': self.user, 'password': self.pwd, 'next': '/404/'})
        self.assertEqual(res.status_code, 302)

    def test_logout(self):
        self.assertIsNone(self.client.logout())

        self.client.login(username=self.user, password=self.pwd)
        self.assertIsNone(self.client.logout())
Пример #24
0
    def test_vote_api(self):
        test_thread_1 = Discussion.objects.create(
            title='This1',
            username='that',
            description='the other thing',
        )

        comment = Comment.objects.create(
            discussion=test_thread_1,
            text='parent',
            username='guy1',
            score=0,
        )

        upvote = {
            "direction": "up",
            "comment_id": str(comment.id)
        }
        client = Client()
        client.post(reverse('vote_comment', kwargs=upvote))

        # Refresh comment from the database
        comment = Comment.objects.get(id=comment.id)

        self.assertEqual(comment.score, 1)

        downvote = {
            "direction": "down",
            "comment_id": str(comment.id)
        }
        client.post(reverse('vote_comment', kwargs=downvote))
        comment = Comment.objects.get(id=comment.id)

        self.assertEqual(comment.score, 0)
class TestURNSubmissionFailureMessage(TestCase):
    def setUp(self):
        self.court = Court.objects.create(
            court_code="0000",
            region_code="06",
            court_name="test court",
            court_address="test address",
            court_telephone="0800 MAKEAPLEA",
            court_email="court@example.org",
            submission_email="court@example.org",
            plp_email="plp@example.org",
            enabled=True,
            display_case_data=True,
            validate_urn=True,
            test_mode=False)

        self.case = Case.objects.create(
            urn="06YY0000000",
            imported=True
        )

        self.client = Client()

    def test_single_failure_no_message(self):
        response = self.client.post('/plea/enter_urn/', data=dict(urn="06xx0000000"))

        self.assertContains(response, "You need to fix the errors on this page before continuing.")
        self.assertNotContains(response, "Your reference number has not been recognised")

    def test_message_appears_after_multiple_failures(self):

        for i in range(3):
            response = self.client.post('/plea/enter_urn/', data=dict(urn="06xx0000000"))

        self.assertContains(response, "Your reference number has not been recognised")
Пример #26
0
 def test_ip_address(self):
     """Test the ip address."""
     client = Client()
     client.post('/with_ip', REMOTE_ADDR='10.10.10.10')
     all_visitors = Visitor.objects.all()
     self.assertEqual(len(all_visitors), 1)
     self.assertEqual(all_visitors[0].ip_address, '10.10.10.10')
Пример #27
0
class WebhooksPOST_TestCase(TestCase):

    def setUp(self):
        self.client = Client()
        factories.models.User.update_friends = Mock()

    def tearDown(self):
        factories.models.User.update_friends = origin_update_friends

    def _get_body(self, obj='user', entry={'id': -1}):
        return dumps({
            'object': obj,
            'entry': [entry]
        })

    def _get_signature(self, body):
        key = settings.SOCIAL_AUTH_FACEBOOK_SECRET
        return "sha1={}".format(hmac.new(key, body, sha1).hexdigest())

    def test_update_ok(self):
        user = factories.UsersFactory.create()
        body = self._get_body(entry={'id': user.uid})

        signature = self._get_signature(body)

        url = reverse('webhooks', )
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': signature})
        self.assertEqual(response.content, 'Ok')
        self.assertEqual(response.status_code, 200)
        self.assertTrue(user.update_friends.called)

    def test_update_fails_with_wrong_body(self):
        body = self._get_body(obj='wrong object')
        url = reverse('webhooks', )
        response = self.client.post(url, body, content_type="application/json")
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid webhook')

    def test_update_fails_with_wrong_uid(self):
        body = self._get_body()
        url = reverse('webhooks', )
        signature = self._get_signature(body)
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': signature})
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid user id')

    def test_update_fails_with_wrong_signature(self):
        user = factories.UsersFactory.create()
        body = self._get_body(entry={'id': user.uid})
        url = reverse('webhooks', )
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': 'sha1=invalid'})
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid signature')
        self.assertFalse(user.update_friends.called)
Пример #28
0
 def test_user_agent(self):
     """Test the user agent."""
     client = Client()
     client.post('/with_user_agent', HTTP_USER_AGENT='Some User Agent')
     all_visitors = Visitor.objects.all()
     self.assertEqual(len(all_visitors), 1)
     self.assertEqual(all_visitors[0].user_agent, 'Some User Agent')
Пример #29
0
    def test_password_reset(self):
        """
        Tests the forgotten/reset password workflow.
        """

        c = Client()

        resp = c.get(reverse('password_reset'))
        self.assertTrue(resp.status_code, 200)

        resp = c.post(reverse('password_reset'), data={'email': 'test@example.com'})
        self.assertEqual(resp.status_code, 302)

        self.assertEqual(len(mail.outbox), 1)

        token = resp.context[0]['token']
        uid = resp.context[0]['uid']

        # Grab the token and uidb64 so that we can hit the reset url
        resp = c.get(reverse('password_reset_confirm', kwargs={'token': token, 'uidb64': uid}))
        self.assertEqual(resp.status_code, 200)
        self.assertTrue(resp.template_name.endswith('password_reset_confirm.html'))

        resp = c.post(reverse('password_reset_confirm', kwargs={'token': token, 'uidb64': uid}),
                      {'new_password1': 'mynewpassword', 'new_password2': 'mynewpassword'})
        self.assertEqual(resp.status_code, 302)
        self.assertEqual(resolve(urlsplit(resp.url).path).url_name, 'password_reset_complete')

        resp = c.post(reverse('login'), {'username': 'tester_mcgee', 'password': 'mynewpassword'})

        # User is returned to the login page on error vs redirected by default
        self.assertEqual(resp.status_code, 302)
        self.assertNotEqual(resolve(urlsplit(resp.url).path).url_name, 'login')
class BackOfficeBackend(TestCase):
    def setUp(self):
        user, created = User.objects.get_or_create(username='admin',
                                                   password='admin',
                                                   first_name='Admin',
                                                   last_name='User',
                                                   email='admin@example.com',
                                                   is_active=True,
                                                   is_staff=True,
                                                   is_superuser=True)
        user.set_password('admin')
        user.save()

        self.user2, created2 = User.objects.get_or_create(username='admin2',
                                                     password='admin',
                                                     first_name='Admin2',
                                                     last_name='User',
                                                     email='admin2@example.com',
                                                     is_active=True,
                                                     is_staff=True,
                                                     is_superuser=True)
        self.user2.set_password('admin')
        self.user2.save()

        self.home_url = reverse(test_backoffice.name + ':home', current_app=test_backoffice.app_name)
        self.client = Client()
        self.client.post(self.home_url, {'username': 'admin', 'password': 'admin'})

    def _reverse(self, name, args=None, kwargs=None):
        pass

    def test_default_context(self):
        """The default context contains usable values"""
        context = test_backoffice.default_context()
        self.assertEqual(context['backoffice'], test_backoffice)
        self.assertTrue('api_url' in context)
        self.assertTrue('root_url' in context)

    def test_home_view(self):
        response = self.client.get(self.home_url)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Hi, <strong>Admin</strong>', response.content)

    def test_default_define_urls(self):
        self.assertEqual(BackOfficeBase().define_urls(), ())

    def test_login_as(self):
        self.client.get(self.home_url + 'login/as/' + six.text_type(self.user2.pk) + '/')
        response = self.client.get(self.home_url, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Hi, <strong>Admin2</strong>', response.content)
        response = self.client.get(self.home_url + 'end/login/as/', follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Hi, <strong>Admin</strong>', response.content)
        self.client.get(self.home_url + 'end/login/as/')

    def test_logout(self):
        response = self.client.get(self.home_url + 'logout/')
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('Hi,', response.content)