Exemple #1
0
class Login_Test(TestCase):
    fixtures = ['test_users.json']

    def test_forbidden_access(self):
        """Go to site withoug logged in."""
        self.client = Client()
        response = self.client.get('/')
        self.assertRedirects(response, '/login?next=/') 

    def test_login(self):
        """Log in."""
        self.client = Client()
        response = self.client.post('/login', {'username':'******','password':'******'})
        self.assertRedirects(response, '/') 
        self.assertEqual(response.status_code, 302, 'Bad response code from login page')

        response = self.client.get('/')
        self.assertEqual(response.status_code, 200, "Logged in user can't access to website.")

    def test_logout(self):
        """Log out."""
        self.client = Client()
        response = self.client.post('/login', {'username':'******','password':'******'})

        response = self.client.get('/logout')
        self.assertRedirects(response, '/login') 

        response = self.client.get('/')
        self.assertNotEqual(response.status_code, 200, "User can access after logout")
Exemple #2
0
class TestNewsletterFunction(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_get_form(self):
        response = self.client.get('/en-US/base/')
        doc = pq(response.content)
        assert_false(doc('#footer-email-errors'))
        ok_(doc('form#footer-email-form'))

    @patch.object(basket, 'subscribe', Mock())
    def test_post_correct_form(self):
        data = {
            'newsletter-footer': 'Y',
            'newsletter': 'mozilla-and-you',
            'email': '*****@*****.**',
            'fmt': 'H',
            'privacy': 'Y',
        }
        response = self.client.post('/en-US/base/', data)
        doc = pq(response.content)
        assert_false(doc('form#footer-email-form'))
        ok_(doc('div#footer-email-form.thank'))

    def test_post_wrong_form(self):
        response = self.client.post('/en-US/base/', {'newsletter-footer': 'Y'})
        doc = pq(response.content)
        ok_(doc('#footer-email-errors'))
        ok_(doc('#footer-email-form.has-errors'))
Exemple #3
0
class AuthTests(TestCase):
    def setUp(self):
        self.c = Client()
        self.password = User.objects.make_random_password()
        self.username = "******"
        self.email = "*****@*****.**"
        u = User.objects.create_user(self.username, self.email, self.password)
        u.is_staff = True
        u.save()

    def tearDown(self):
        User.objects.get(username=self.username).delete()
    
    def testAddUser(self):
        testcase_username = '******'
        testcase_password = User.objects.make_random_password()
        
        self.c.login(username=self.username, password=self.password)
        self.c.post('http://uwcs.co.uk/admin/auth/user/add/', {
            'username':testcase_username, 
            'password1':testcase_password, 
            'password2':testcase_password
        })
        #User.objects.get(username=testcase_username).delete()


    def testLogin(self):
       self.assertContains(self.c.post('/login/', {"username": self.username, "password": self.password, "next":""}, follow=True), "Logged in as")
Exemple #4
0
    def test_email_verification_mandatory(self):
        c = Client()
        # Signup
        resp = c.post(
            reverse("account_signup"),
            {"username": "******", "email": "*****@*****.**", "password1": "johndoe", "password2": "johndoe"},
            follow=True,
        )
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(mail.outbox[0].to, ["*****@*****.**"])
        self.assertGreater(mail.outbox[0].body.find("https://"), 0)
        self.assertEqual(len(mail.outbox), 1)
        self.assertTemplateUsed(resp, "account/verification_sent.html")
        # Attempt to login, unverified
        for attempt in [1, 2]:
            resp = c.post(reverse("account_login"), {"login": "******", "password": "******"}, follow=True)
            # is_active is controlled by the admin to manually disable
            # users. I don't want this flag to flip automatically whenever
            # users verify their email adresses.
            self.assertTrue(get_user_model().objects.filter(username="******", is_active=True).exists())

            self.assertTemplateUsed(resp, "account/verification_sent.html")
            # Attempt 1: no mail is sent due to cool-down ,
            # but there was already a mail in the outbox.
            self.assertEqual(len(mail.outbox), attempt)
            self.assertEqual(EmailConfirmation.objects.filter(email_address__email="*****@*****.**").count(), attempt)
            # Wait for cooldown
            EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
        # Verify, and re-attempt to login.
        confirmation = EmailConfirmation.objects.filter(email_address__user__username="******")[:1].get()
        resp = c.get(reverse("account_confirm_email", args=[confirmation.key]))
        self.assertTemplateUsed(resp, "account/email_confirm.html")
        c.post(reverse("account_confirm_email", args=[confirmation.key]))
        resp = c.post(reverse("account_login"), {"login": "******", "password": "******"})
        self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL)
Exemple #5
0
 def test_optional_email_verification(self):
     c = Client()
     # Signup
     c.get(reverse('account_signup'))
     resp = c.post(reverse('account_signup'),
                   {'username': '******',
                    'email': '*****@*****.**',
                    'password1': 'johndoe',
                    'password2': 'johndoe'})
     # Logged in
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     self.assertEqual(len(mail.outbox), 1)
     # Logout & login again
     c.logout()
     # Wait for cooldown
     EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
     # Signup
     resp = c.post(reverse('account_login'),
                   {'login': '******',
                    'password': '******'})
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     # There was an issue that we sent out email confirmation mails
     # on each login in case of optional verification. Make sure
     # this is not the case:
     self.assertEqual(len(mail.outbox), 1)
Exemple #6
0
class TestLogin(TransactionTestCase):
    fixtures = ['init_panda.json']

    def setUp(self):
        self.user = utils.get_panda_user()
        
        self.client = Client()

    def test_login_success(self):
        response = self.client.post('/login/', { 'email': '*****@*****.**', 'password': '******' }) 

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertEqual(body['email'], '*****@*****.**')
        self.assertEqual(body['api_key'], 'edfe6c5ffd1be4d3bf22f69188ac6bc0fc04c84c')
        self.assertEqual(body['notifications'], [])

    def test_login_disabled(self):
        self.user.is_active = False
        self.user.save()

        response = self.client.post('/login/', { 'email': '*****@*****.**', 'password': '******' }) 

        self.assertEqual(response.status_code, 400)

        body = json.loads(response.content)

        self.assertIn('disabled', body['__all__'])

        self.user.is_active = True
        self.user.save()

    def test_login_invalid_email(self):
        response = self.client.post('/login/', { 'email': '*****@*****.**', 'password': '******' }) 

        self.assertEqual(response.status_code, 400)

        body = json.loads(response.content)

        self.assertIn('incorrect', body['__all__'])

    def test_login_incorrect_password(self):
        response = self.client.post('/login/', { 'email': '*****@*****.**', 'password': '******' }) 

        self.assertEqual(response.status_code, 400)

        body = json.loads(response.content)

        self.assertIn('incorrect', body['__all__'])

    def test_no_get(self):
        response = self.client.get('/login/', { 'email': '*****@*****.**', 'password': '******' }) 

        self.assertEqual(response.status_code, 400)

        body = json.loads(response.content)

        self.assertEqual(body, None)
Exemple #7
0
    def test_confirm(self):
        c = Client()
        acc = Account()
        acc.username='******'
        acc.password='******'
        acc.fullname='foouser'
        acc.created = datetime.datetime.now()
        acc.contract = '010001'
        acc.save()
        TransactionType.objects.create(name='EasyPay', internal_name = 'payments.easypay')
        
        response = c.post(reverse('getpaid-easypay-pay'), """<Request>
<DateTime>yyyy-MM-ddTHH:mm:ss</DateTime>
<Sign></Sign>
<Payment>
<ServiceId>1</ServiceId>
<OrderId>1</OrderId>
<Account>010001</Account>
<Amount>10.11</Amount>
</Payment>
</Request>""", content_type='text/xml')
        print response.content
        bs = BeautifulSoup(response.content)
        response = c.post(reverse('getpaid-easypay-pay'), """<Request>
<DateTime>yyyy-MM-ddTHH:mm:ss</DateTime>
<Sign></Sign>
<Confirm>
<ServiceId>1</ServiceId>
<PaymentId>%s</PaymentId>
</Confirm>
</Request>""" % bs.response.paymentid, content_type='text/xml')
        
        print 'TRANSACTION=', Transaction.objects.get(type__internal_name='payments.easypay', bill='1')
        
        print response.content
Exemple #8
0
 def testUnicodeTraceback(self):
     c = Client()
     assert not Error.objects.count()
     ldata = data.copy()
     ldata["traceback"] = "ɷo̚حٍ"
     c.post(reverse("error-post"), ldata)
     assert Error.objects.count() == 1
    def testEditChanges(self):
        user, info = test_user()
        _, change_info = test_user(create=False)

        c = Client()
        self.assertTrue(c.login(username=info['username'],
                                password=info['password']), "Can't log in?")

        c.post(reverse('account:edit'), {
            'email': change_info['email'],
            'preferred_name': change_info['preferred_name'],
            'real_name': change_info['real_name'],
        })

        # refresh the user
        # user.refresh_from_db() # we don't get this until dj1.8...
        user = User.objects.get(pk=user.pk)
        self.assertFalse(user.userdata.email_verified)
        self.assertTrue(user.emailverification_set.all().exists())
        self.assertEqual(user.first_name, user.userdata.preferred_name)
        self.assertEqual(user.last_name, '')
        self.assertEqual(user.userdata.preferred_name,
                         change_info['preferred_name'])
        self.assertEqual(user.userdata.real_name, change_info['real_name'])
        self.assertEqual(user.email, change_info['email'])
Exemple #10
0
 def testNoPriority(self):
     c = Client()
     assert not Error.objects.count()
     ldata = data.copy()
     del ldata["priority"]
     c.post(reverse("error-post"), ldata)
     assert Error.objects.count() == 1
Exemple #11
0
 def testGroupDelete(self):
     c = Client()
     c.post(reverse("error-post"), data)
     assert Group.objects.count() == 1, "Got %s groups, not 1" % Group.objects.count()
     assert Error.objects.count() == 1
     Error.objects.all()[0].delete()
     assert Group.objects.count() == 0
Exemple #12
0
    def test_upload(self):
        c = Client()

        url = reverse('gbd.covariate_data_server.views.covariate_upload')
        response = c.get(url)
        self.assertRedirects(response, '/accounts/login/?next=%s'%url)
        # then login and do functional tests
        c.login(username='******', password='******')

        response = c.get(url)
        self.assertTemplateUsed(response, 'covariate_upload.html')

        response = c.post(url, {})
        self.assertTemplateUsed(response, 'covariate_upload.html')

        # now do it right, and make sure that data and datasets are added
        from StringIO import StringIO
        f = StringIO(',iso3,year,LDI_id,LDI_usd\n1,ABW,1950,1533.743774,1105.747437\n1,ABW,1951,1533.843774,1105.87437\n')
        f.name = 'LDI.csv'
        response = c.post(url, {'file':f, 'type': 'LDI_id', 'source': 'web', 'notes': 'description', 'uploader': 'red', 'yearStart': 1950, 'yearEnd': 2010})
        self.assertRedirects(response, reverse('gbd.covariate_data_server.views.covariate_type_list_show'))
        self.assertEqual(CovariateType.objects.filter(slug='LDI_id').count(), 1)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='male').count(), 2)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='female').count(), 2)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='total').count(), 2)
Exemple #13
0
class TVTestCase(unittest.TestCase):

    def setUp(self):
        contracts = Contract.objects.all()
        self.contracts = []
        for contract in contracts:
            if contract.is_open():
                self.contracts.append(contract)

    	self.client = Client()
            	
    def test_tv(self):      
        for contract in self.contracts:
            self.client.post('/login', {'contract': contract.contract, 'password': contract.password})
            response = self.client.get('/tv')

            service = Service(contract=contract)

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

            title_exist   = True if 'Произошла ошибка!' in response.content else False
            message_exist = True if 'Данная услуга у вас не привязана к данному логину. Предварительно осуществите привязку.' in response.content else False

            if service.is_tv_activated():
                self.assertEqual(title_exist, False)
                self.assertEqual(message_exist, False)
            else:
                self.assertEqual(title_exist, True)
                self.assertEqual(message_exist, True)                

            #logout
            self.client.post('/logout')
Exemple #14
0
    def test_update_items_users(self):
        client = Client()

        users = get_model('main', 'users')
        user = users(name="test", paycheck=1000, date_joined=timezone.now())
        user.save()

        data = {'id': 1, 'field': 'name', 'value': "test2"}
        res = client.post('/users/', data)
        self.assertEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(users.objects.first().name, 'test2')

        data = {'id': 1, 'field': 'paycheck', 'value': "500"}
        res = client.post('/users/', data)
        self.assertEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(users.objects.first().paycheck, 500)

        data = {'id': 1, 'field': 'paycheck', 'value': "bbb"}
        res = client.post('/users/', data)
        self.assertEqual(
            json.loads(res.content)['message'], 'Value is in wrong format'
        )

        data = {'id': 1, 'field': 'date_joined', 'value': "10-05-2012"}
        res = client.post('/users/', data)
        self.assertEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(users.objects.first().date_joined, datetime.date(2012, 5, 10))

        data = {'id': 1, 'field': 'date_joined', 'value': "10052012"}
        res = client.post('/users/', data)
        self.assertEqual(
            json.loads(res.content)['message'], 'Value is in wrong format'
        )
Exemple #15
0
    def test_translated_competition_entry_stored_against_the_main_lang(self):
        client = Client()
        client.login(username='******', password='******')

        en_comp = YourWordsCompetition(
            title='Test Competition',
            description='This is the description',
            slug='test-competition')
        self.competition_index.add_child(instance=en_comp)
        en_comp.save_revision().publish()

        self.client.post(reverse(
            'add_translation', args=[en_comp.id, 'fr']))
        fr_comp = YourWordsCompetition.objects.get(
            slug='french-translation-of-test-competition')
        fr_comp.save_revision().publish()

        client.post(
            reverse('molo.yourwords:competition_entry', args=[fr_comp.slug]), {
                'story_name': 'this is a french story',
                'story_text': 'The text',
                'terms_or_conditions_approved': 'true'})

        entry = YourWordsCompetitionEntry.objects.all().first()
        self.assertEqual(entry.story_name, 'this is a french story')
        self.assertEqual(entry.competition.id, en_comp.id)
    def test_25_page_admin_view(self):
        """Test page admin view"""
        c = Client()
        c.login(username= '******', password='******')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page-1'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, 1)
        response = c.post('/admin/pages/page/%d/change-status/' %
            page.id, {'status':Page.DRAFT})
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, Page.DRAFT)

        url = '/admin/pages/page/%d/modify-content/title/en-us/' % page.id
        response = c.post(url, {'content': 'test content'})
        self.assertEqual(page.title(), 'test content')

        # TODO: realy test these methods
        url = '/admin/pages/page/%d/traduction/en-us/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)
        
        url = '/admin/pages/page/%d/sub-menu/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)

        url = '/admin/pages/page/%d/get-content/1/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)
Exemple #17
0
    def test_update_items_rooms(self):
        client = Client()

        rooms = get_model('main', 'rooms')
        room = rooms(department="test", spots=1000, owner='Budda')
        room.save()

        data = {'id': 1, 'field': 'department', 'value': "test2"}
        res = client.post('/rooms/', data)
        self.assertDictEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(rooms.objects.first().department, 'test2')

        data = {'id': 1, 'field': 'spots', 'value': "500"}
        res = client.post('/rooms/', data)
        self.assertEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(rooms.objects.first().spots, 500)

        data = {'id': 1, 'field': 'spots', 'value': "bbb"}
        res = client.post('/rooms/', data)
        self.assertEqual(
            json.loads(res.content)['message'], 'Value is in wrong format'
        )

        data = {'id': 1, 'field': 'owner', 'value': "Boom"}
        res = client.post('/rooms/', data)
        self.assertEqual(json.loads(res.content), {'status': 'OK'})
        self.assertEqual(rooms.objects.first().owner, "Boom")
Exemple #18
0
class AutoModelMixinViewsTest(TestCase):
    urls = 'tests.urls'

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

    def test_list_view(self):
        self.assertRaisesMessage(TemplateDoesNotExist, 'tests/testmodelc_list.html', self.client.get, '/test_model/test_model_c/')

    def test_create_view(self):
        self.assertRaisesMessage(TemplateDoesNotExist, 'tests/testmodelc_form.html', self.client.get, '/test_model/test_model_c/create/')
        response = self.client.post('/test_model/test_model_c/create/', {'name': 'aar7iNgou2viw4ahv2ve'})
        self.assertEqual(response.url, 'http://testserver/test_model/test_model_c/1/')
        self.assertTrue(TestModelC.objects.filter(name='aar7iNgou2viw4ahv2ve').exists())

    def test_detail_view(self):
        TestModelC.objects.create(name='AiwaiB5oheez1UJajeip')
        self.assertRaisesMessage(TemplateDoesNotExist, 'tests/testmodelc_detail.html', self.client.get, '/test_model/test_model_c/1/')

    def test_update_view(self):
        TestModelC.objects.create(name='Luph3tohquoesai2haLa')
        self.assertRaisesMessage(TemplateDoesNotExist, 'tests/testmodelc_form.html', self.client.get, '/test_model/test_model_c/1/update/')
        response = self.client.post('/test_model/test_model_c/1/update/', {'name': 'apeej7eiGhab3eipheem'})
        self.assertEqual(response.url, 'http://testserver/test_model/test_model_c/1/')
        self.assertFalse(TestModelC.objects.filter(name='Luph3tohquoesai2haLa').exists())
        self.assertTrue(TestModelC.objects.filter(name='apeej7eiGhab3eipheem').exists())

    def test_delete_view(self):
        TestModelC.objects.create(name='Zah6ceiGiu0ahf7ouH4h')
        self.assertTrue(TestModelC.objects.filter(name='Zah6ceiGiu0ahf7ouH4h').exists())
        self.assertRaisesMessage(TemplateDoesNotExist, 'tests/testmodelc_confirm_delete.html', self.client.get, '/test_model/test_model_c/1/delete/')
        response = self.client.post('/test_model/test_model_c/1/delete/', {})
        self.assertEqual(response.url, 'http://testserver/test_model/test_model_c/')
        self.assertFalse(TestModelC.objects.filter(name='Zah6ceiGiu0ahf7ouH4h').exists())
    def test_06_site_framework(self):
        """Test the site framework, and test if it's possible to
        disable it"""

        # this is necessary to make the test pass
        from pages import settings as pages_settings
        setattr(pages_settings, "SITE_ID", 2)
        setattr(pages_settings, "PAGE_USE_SITE_ID", True)

        c = Client()
        c.login(username= '******', password='******')
        page_data = self.get_new_page_data()
        page_data["sites"] = [2]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 2)

        page_data = self.get_new_page_data()
        page_data["sites"] = [3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # we cannot get a slug that doesn't exist
        content = Content.objects.get_content_slug_by_slug("this doesn't exist")
        self.assertEqual(content, None)

        # we cannot get the data posted on another site
        content = Content.objects.get_content_slug_by_slug(page_data['slug'])
        self.assertEqual(content, None)

        setattr(pages_settings, "SITE_ID", 3)
        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 3)

        # with param
        self.assertEqual(Page.objects.on_site(2).count(), 1)
        self.assertEqual(Page.objects.on_site(3).count(), 1)

        # without param
        self.assertEqual(Page.objects.on_site().count(), 1)
        setattr(pages_settings, "SITE_ID", 2)
        self.assertEqual(Page.objects.on_site().count(), 1)

        page_data = self.get_new_page_data()
        page_data["sites"] = [2, 3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        self.assertEqual(Page.objects.on_site(3).count(), 2)
        self.assertEqual(Page.objects.on_site(2).count(), 2)
        self.assertEqual(Page.objects.on_site().count(), 2)

        setattr(pages_settings, "PAGE_USE_SITE_ID", False)

        # we should get everything
        self.assertEqual(Page.objects.on_site().count(), 3)
Exemple #20
0
class TestLoginWithHadoop(PseudoHdfsTestBase):

  def setUp(self):
    # Simulate first login ever
    User.objects.all().delete()
    self.c = Client()

  def test_login(self):
    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true(response.context['first_login_ever'])

    response = self.c.post('/accounts/login/', dict(username="******", password="******"))
    assert_equal(302, response.status_code, "Expected ok redirect status.")
    assert_true(self.fs.exists("/user/foo"))

    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_false(response.context['first_login_ever'])

  def test_login_home_creation_failure(self):
    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true(response.context['first_login_ever'])

    # Create home directory as a file in order to fail in the home creation later
    cluster = pseudo_hdfs4.shared_cluster()
    fs = cluster.fs
    assert_false(cluster.fs.exists("/user/foo2"))
    fs.do_as_superuser(fs.create, "/user/foo2")

    response = self.c.post('/accounts/login/', dict(username="******", password="******"), follow=True)
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true('/beeswax' in response.content, response.content)
Exemple #21
0
def test_django():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings")
    sys.path.append(
        os.path.join(
            os.path.abspath(os.path.dirname(__file__)), 'django_test_env'
        )
    )

    from django.test.utils import setup_test_environment
    setup_test_environment()
    from django.test.client import Client
    from werobot.parser import parse_xml, process_message
    import django

    django.setup()
    client = Client()

    token = 'TestDjango'
    timestamp = str(time.time())
    nonce = str(random.randint(0, 10000))
    signature = get_signature(token, timestamp, nonce)
    echostr = generate_token()

    response = client.get(
        '/robot/', {
            'signature': signature,
            'timestamp': timestamp,
            'nonce': nonce,
            'echostr': echostr
        }
    )
    assert response.status_code == 200
    assert response.content.decode('utf-8') == echostr

    xml = """
    <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[fromUser]]></FromUserName>
        <CreateTime>1348831860</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[this is a test]]></Content>
        <MsgId>1234567890123456</MsgId>
    </xml>"""
    params = "?timestamp=%s&nonce=%s&signature=%s" % \
             (timestamp, nonce, signature)
    url = '/robot/'
    response = client.post(url, data=xml, content_type="text/xml")

    assert response.status_code == 403
    assert response.content.decode('utf-8') == u'喵'

    url += params
    response = client.post(url, data=xml, content_type="text/xml")

    assert response.status_code == 200
    response = process_message(parse_xml(response.content))
    assert response.content == 'hello'

    response = client.options(url)
    assert response.status_code == 405
class MockedPayPalTests(TestCase):
    response_body = None

    def setUp(self):
        self.client = Client()
        with patch('requests.post') as post:
            self.patch_http_post(post)
            self.perform_action()

    def patch_http_post(self, post):
        post.return_value = self.get_mock_response()

    def get_mock_response(self, content=None):
        response = Mock()
        response.content = self.response_body if content is None else content
        response.status_code = 200
        return response

    def perform_action(self):
        pass

    def add_product_to_basket(self, price=D('100.00')):
        product = create_product(price=price)
        self.client.post(reverse('basket:add'),
                                 {'product_id': product.id,
                                  'quantity': 1})
Exemple #23
0
 def test_proxy_ip(self):
     client2 = Client(REMOTE_ADDR="127.0.0.1", HTTP_X_FORWARDED_FOR="1.2.3.4")
     self.failUnless(client2.login(username="******", password="******"))
     client2.post("/upload", {"data_file": make_song("music1.mp3", "..data..")})
     song_code = Song.objects.get(original_name="music1.mp3").get_code()
     event = self.events[0]
     self.failUnlessEqual(event["ip"], "1.2.3.4")
Exemple #24
0
class FormTest(TestCase):
    """ Tests for forms """
    def setUp(self):
        self.client = Client()

    def test_task_form_opens(self):
        response = self.client.get('/new_task/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'new_task.html', 'base.html')

    def test_story_form_opens(self):
        response = self.client.get('/new_story/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'new_story.html', 'base.html')

    def test_task_form_fails(self):
        story = Story.objects.create(story_name='Story 1', 
                                     time_est=dt.datetime(2015, 6, 1, 12))
        response = self.client.post('/new_task/', {'task_name':'Task',
                                                   'time_est': 'invalid_time',
                                                   'developer': Task.DEVELOPERS[0][0],
                                                   'iteration': 1,
                                                   'story': story}, follow=True)

        self.assertFormError(response, 'form', 'time_est', 'Enter valid deadline (eg.: 2015-05-17 10:35)')

    def test_task_form_passes(self):
        story = Story.objects.create(story_name='Story 1', 
                                     time_est=dt.datetime(2015, 6, 1, 12))
        response = self.client.post('/new_task/', {'task_name':'Task',
                                                   'time_est': dt.datetime(2015, 4, 23, 12, 15),
                                                   'developer': Task.DEVELOPERS[0][0],
                                                   'iteration': 1,
                                                   'story': story}, follow=True)
Exemple #25
0
class SubscriptionTest(TestCase):
    def setUp(self):
        self.client = Client()


    def test_subscription_add_an_email(self):
        self.assertEqual(Subscription.objects.count(), 0)

        response = self.client.post(reverse('subscribe'),
                                    data={'email':'*****@*****.**'})
        self.assertEqual(Subscription.objects.count(), 1)


    def test_unsubscription_remove_email(self):
        Subscription.objects.create(email="*****@*****.**")

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

        self.assertEqual(Subscription.objects.count(), 0)


    def test_only_one_email_are_bubscribed(self):
        Subscription.objects.create(email="*****@*****.**")
        response = self.client.post(reverse('subscribe'),
                                        data={'email':'*****@*****.**'})
        form = response.context['form']
        self.assertEqual(form.errors['email'], [u'E-mail already registered'])
class BasicViewsTest(TestCase):
	fixtures = ["auth.json", "sites.json"]
	
	def setUp(self):
		self.client = Client()

	def tearDown(self):
		pass
	
	def test_status_listeners(self):
		self.failUnless(StatusListener.objects.all().count() == 0)

		response = self.client.post(APP_PATH, {'register':8088})
		self.failUnlessEqual(response.status_code, 200, 'status was %s' % response.status_code )
		self.failUnless('flock/status.html' in [template.name for template in response.template])
		self.failUnless(StatusListener.objects.all().count() == 1)
		sl = StatusListener.objects.all()[0]
		self.failUnlessEqual(sl.host, '127.0.0.1:8088')
		self.failUnlessEqual(len(sl.tests.all()), 0)
		
		response = self.client.post(APP_PATH, {'unregister':8088})
		self.failUnlessEqual(response.status_code, 200, 'status was %s' % response.status_code )
		self.failUnless('flock/status.html' in [template.name for template in response.template])
		self.failUnless(StatusListener.objects.all().count() == 0)

		response = self.client.post(APP_PATH, {'register':8088, 'tests':'test1,test2,test3'})
		self.failUnlessEqual(response.status_code, 200, 'status was %s' % response.status_code )
		self.failUnless('flock/status.html' in [template.name for template in response.template])
		self.failUnless(StatusListener.objects.all().count() == 1)
		sl = StatusListener.objects.all()[0]
		self.failUnlessEqual(len(sl.tests.all()), 3)
		self.failUnless('test2' in [test.name for test in sl.tests.all()])
    def test001_possible_changes_loose_in_ReferenceField_clean_method(self):
        # drop any parent present
        Test001Parent.objects.delete()

        # prepare two test parents
        parent1 = Test001Parent(name='parent1')
        parent1.save()
        parent2 = Test001Parent(name='parent2')
        parent2.save()

        # prepare test client
        c = Client()

        # post form with first parent and empty name
        response = c.post('/test001/', {'parent': parent1.pk})

        # assert first parent is selected
        self.assertEqual(response.context['form'].data['parent'],
            unicode(parent1.pk), 'first parent must be selected')

        # post form with second parent and empty name
        response = c.post('/test001/', {'parent': parent2.pk})

        # assert second parent is selected
        self.assertEqual(response.context['form'].data['parent'],
            unicode(parent2.pk), 'second parent must be selected')
Exemple #28
0
    def test_map_save(self):
        """POST /maps -> Test saving a new map"""

        c = Client()

        # Test that saving a map when not logged in gives 401
        response = c.post("/maps/",data=MapTest.viewer_config,content_type="text/json")
        self.assertEqual(response.status_code,401)

        # Test successful new map creation
        c.login(username="******", password="******")
        response = c.post("/maps/",data=MapTest.viewer_config,content_type="text/json")
        self.assertEquals(response.status_code,201)
        map_id = int(response['Location'].split('/')[-1])
        c.logout()

        self.assertEquals(map_id,2)
        map_obj = Map.objects.get(id=map_id)
        self.assertEquals(map_obj.title, "Title")
        self.assertEquals(map_obj.abstract, "Abstract")
        self.assertEquals(map_obj.layer_set.all().count(), 1)
        self.assertEquals(map_obj.keyword_list(), ["keywords", "saving"])

        # Test an invalid map creation request
        c.login(username="******", password="******")
        response = c.post("/maps/",data="not a valid viewer config",content_type="text/json")
        self.assertEquals(response.status_code,400)
        c.logout()
Exemple #29
0
 def test_optional_email_verification(self):
     c = Client()
     # Signup
     c.get(reverse("account_signup"))
     resp = c.post(
         reverse("account_signup"),
         {"username": "******", "email": "*****@*****.**", "password1": "johndoe", "password2": "johndoe"},
     )
     # Logged in
     self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL)
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(mail.outbox[0].to, ["*****@*****.**"])
     self.assertEqual(len(mail.outbox), 1)
     # Logout & login again
     c.logout()
     # Wait for cooldown
     EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
     # Signup
     resp = c.post(reverse("account_login"), {"login": "******", "password": "******"})
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL)
     self.assertEqual(mail.outbox[0].to, ["*****@*****.**"])
     # There was an issue that we sent out email confirmation mails
     # on each login in case of optional verification. Make sure
     # this is not the case:
     self.assertEqual(len(mail.outbox), 1)
Exemple #30
0
    def test_delete_profile(self):
        """Test profile deletion."""
        # user can't delete own profile
        c = Client()
        c.login(username='******', password='******')
        response = c.post(self.user_delete_url, follow=True)
        self.assertTemplateUsed(response, 'main.html')
        for m in response.context['messages']:
            pass
        eq_(m.tags, u'error')

        # admin can delete user's profile
        c = Client()
        c.login(username='******', password='******')
        response = c.post(self.user_delete_url, {'delete': 'true'},
                          follow=True)
        self.assertTemplateUsed(response, 'main.html')
        for m in response.context['messages']:
            pass
        eq_(m.tags, u'success')

        # third user can't delete user's profile
        c = Client()
        c.login(username='******', password='******')
        response = c.post(self.user_delete_url, follow=True)
        self.assertTemplateUsed(response, 'main.html')
        for m in response.context['messages']:
            pass
        eq_(m.tags, u'error')
Exemple #31
0
class ViewsTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin):
    @patch.dict("django.conf.settings.FEATURES",
                {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):

        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
        # of the UrlResetMixin)
        super(ViewsTestCase, self).setUp(create_user=False)

        # create a course
        self.course = CourseFactory.create(
            org='MITx',
            course='999',
            discussion_topics={"Some Topic": {
                "id": "some_topic"
            }},
            display_name='Robot Super Course',
        )
        self.course_id = self.course.id
        # seed the forums permissions and roles
        call_command('seed_permissions_roles',
                     self.course_id.to_deprecated_string())

        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = '*****@*****.**'
            password = '******'

            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, password)
            self.student.is_active = True
            self.student.save()

            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)

            self.client = Client()
            assert_true(self.client.login(username='******', password='******'))

    def test_create_thread(self, mock_request):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(
            mock_request, {
                "thread_type": "discussion",
                "title": "Hello",
                "body": "this is a post",
                "course_id": "MITx/999/Robot_Super_Course",
                "anonymous": False,
                "anonymous_to_peers": False,
                "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
                "created_at": "2013-05-10T18:53:43Z",
                "updated_at": "2013-05-10T18:53:43Z",
                "at_position_list": [],
                "closed": False,
                "id": "518d4237b023791dca00000d",
                "user_id": "1",
                "username": "******",
                "votes": {
                    "count": 0,
                    "up_count": 0,
                    "down_count": 0,
                    "point": 0
                },
                "abuse_flaggers": [],
                "type": "thread",
                "group_id": None,
                "pinned": False,
                "endorsed": False,
                "unread_comments_count": 0,
                "read": False,
                "comments_count": 0,
            })
        thread = {
            "thread_type": "discussion",
            "body": ["this is a post"],
            "anonymous_to_peers": ["false"],
            "auto_subscribe": ["false"],
            "anonymous": ["false"],
            "title": ["Hello"],
        }
        url = reverse('create_thread',
                      kwargs={
                          'commentable_id':
                          'i4x-MITx-999-course-Robot_Super_Course',
                          'course_id': self.course_id.to_deprecated_string()
                      })
        response = self.client.post(url, data=thread)
        assert_true(mock_request.called)
        mock_request.assert_called_with(
            'post',
            '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(
                prefix=CS_PREFIX),
            data={
                'thread_type': 'discussion',
                'body': u'this is a post',
                'anonymous_to_peers': False,
                'user_id': 1,
                'title': u'Hello',
                'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course',
                'anonymous': False,
                'course_id': u'MITx/999/Robot_Super_Course',
            },
            params={'request_id': ANY},
            headers=ANY,
            timeout=5)
        assert_equal(response.status_code, 200)

    def test_delete_comment(self, mock_request):
        self._set_mock_request_data(mock_request, {
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_comment_id = "test_comment_id"
        request = RequestFactory().post("dummy_url", {"id": test_comment_id})
        request.user = self.student
        request.view_name = "delete_comment"
        response = views.delete_comment(
            request,
            course_id=self.course.id.to_deprecated_string(),
            comment_id=test_comment_id)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        args = mock_request.call_args[0]
        self.assertEqual(args[0], "delete")
        self.assertTrue(args[1].endswith("/{}".format(test_comment_id)))

    def _setup_mock_request(self, mock_request, include_depth=False):
        """
        Ensure that mock_request returns the data necessary to make views
        function correctly
        """
        mock_request.return_value.status_code = 200
        data = {
            "user_id": str(self.student.id),
            "closed": False,
        }
        if include_depth:
            data["depth"] = 0
        self._set_mock_request_data(mock_request, data)

    def _test_request_error(self, view_name, view_kwargs, data, mock_request):
        """
        Submit a request against the given view with the given data and ensure
        that the result is a 400 error and that no data was posted using
        mock_request
        """
        self._setup_mock_request(
            mock_request, include_depth=(view_name == "create_sub_comment"))

        response = self.client.post(reverse(view_name, kwargs=view_kwargs),
                                    data=data)
        self.assertEqual(response.status_code, 400)
        for call in mock_request.call_args_list:
            self.assertEqual(call[0][0].lower(), "get")

    def test_create_thread_no_title(self, mock_request):
        self._test_request_error(
            "create_thread", {
                "commentable_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"body": "foo"}, mock_request)

    def test_create_thread_empty_title(self, mock_request):
        self._test_request_error(
            "create_thread", {
                "commentable_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {
                "body": "foo",
                "title": " "
            }, mock_request)

    def test_create_thread_no_body(self, mock_request):
        self._test_request_error(
            "create_thread", {
                "commentable_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"title": "foo"}, mock_request)

    def test_create_thread_empty_body(self, mock_request):
        self._test_request_error(
            "create_thread", {
                "commentable_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {
                "body": " ",
                "title": "foo"
            }, mock_request)

    def test_update_thread_no_title(self, mock_request):
        self._test_request_error(
            "update_thread", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"body": "foo"}, mock_request)

    def test_update_thread_empty_title(self, mock_request):
        self._test_request_error(
            "update_thread", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {
                "body": "foo",
                "title": " "
            }, mock_request)

    def test_update_thread_no_body(self, mock_request):
        self._test_request_error(
            "update_thread", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"title": "foo"}, mock_request)

    def test_update_thread_empty_body(self, mock_request):
        self._test_request_error(
            "update_thread", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {
                "body": " ",
                "title": "foo"
            }, mock_request)

    def test_update_thread_course_topic(self, mock_request):
        self._setup_mock_request(mock_request)
        response = self.client.post(reverse(
            "update_thread",
            kwargs={
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }),
                                    data={
                                        "body": "foo",
                                        "title": "foo",
                                        "commentable_id": "some_topic"
                                    })
        self.assertEqual(response.status_code, 200)

    @patch('django_comment_client.base.views.get_discussion_categories_ids',
           return_value=["test_commentable"])
    def test_update_thread_wrong_commentable_id(self,
                                                mock_get_discussion_id_map,
                                                mock_request):
        self._test_request_error(
            "update_thread", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {
                "body": "foo",
                "title": "foo",
                "commentable_id": "wrong_commentable"
            }, mock_request)

    def test_create_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_comment", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {}, mock_request)

    def test_create_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_comment", {
                "thread_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"body": " "}, mock_request)

    def test_create_sub_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment", {
                "comment_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {}, mock_request)

    def test_create_sub_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment", {
                "comment_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"body": " "}, mock_request)

    def test_update_comment_no_body(self, mock_request):
        self._test_request_error(
            "update_comment", {
                "comment_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {}, mock_request)

    def test_update_comment_empty_body(self, mock_request):
        self._test_request_error(
            "update_comment", {
                "comment_id": "dummy",
                "course_id": self.course_id.to_deprecated_string()
            }, {"body": " "}, mock_request)

    def test_update_comment_basic(self, mock_request):
        self._setup_mock_request(mock_request)
        comment_id = "test_comment_id"
        updated_body = "updated body"

        response = self.client.post(reverse(
            "update_comment",
            kwargs={
                "course_id": self.course_id.to_deprecated_string(),
                "comment_id": comment_id
            }),
                                    data={"body": updated_body})

        self.assertEqual(response.status_code, 200)
        mock_request.assert_called_with(
            "put",
            "{prefix}/comments/{comment_id}".format(prefix=CS_PREFIX,
                                                    comment_id=comment_id),
            headers=ANY,
            params=ANY,
            timeout=ANY,
            data={"body": updated_body})

    def test_flag_thread_open(self, mock_request):
        self.flag_thread(mock_request, False)

    def test_flag_thread_close(self, mock_request):
        self.flag_thread(mock_request, True)

    def flag_thread(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(
            mock_request, {
                "title": "Hello",
                "body": "this is a post",
                "course_id": "MITx/999/Robot_Super_Course",
                "anonymous": False,
                "anonymous_to_peers": False,
                "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
                "created_at": "2013-05-10T18:53:43Z",
                "updated_at": "2013-05-10T18:53:43Z",
                "at_position_list": [],
                "closed": is_closed,
                "id": "518d4237b023791dca00000d",
                "user_id": "1",
                "username": "******",
                "votes": {
                    "count": 0,
                    "up_count": 0,
                    "down_count": 0,
                    "point": 0
                },
                "abuse_flaggers": [1],
                "type": "thread",
                "group_id": None,
                "pinned": False,
                "endorsed": False,
                "unread_comments_count": 0,
                "read": False,
                "comments_count": 0,
            })
        url = reverse('flag_abuse_for_thread',
                      kwargs={
                          'thread_id': '518d4237b023791dca00000d',
                          'course_id': self.course_id.to_deprecated_string()
                      })
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (('get', '{prefix}/threads/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'mark_as_read': True,
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                }),
            (('put',
              '{prefix}/threads/518d4237b023791dca00000d/abuse_flag'.format(
                  prefix=CS_PREFIX)), {
                      'data': {
                          'user_id': '1'
                      },
                      'params': {
                          'request_id': ANY
                      },
                      'headers': ANY,
                      'timeout': 5
                  }),
            (('get', '{prefix}/threads/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'mark_as_read': True,
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                })
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_un_flag_thread_open(self, mock_request):
        self.un_flag_thread(mock_request, False)

    def test_un_flag_thread_close(self, mock_request):
        self.un_flag_thread(mock_request, True)

    def un_flag_thread(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(
            mock_request, {
                "title": "Hello",
                "body": "this is a post",
                "course_id": "MITx/999/Robot_Super_Course",
                "anonymous": False,
                "anonymous_to_peers": False,
                "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
                "created_at": "2013-05-10T18:53:43Z",
                "updated_at": "2013-05-10T18:53:43Z",
                "at_position_list": [],
                "closed": is_closed,
                "id": "518d4237b023791dca00000d",
                "user_id": "1",
                "username": "******",
                "votes": {
                    "count": 0,
                    "up_count": 0,
                    "down_count": 0,
                    "point": 0
                },
                "abuse_flaggers": [],
                "type": "thread",
                "group_id": None,
                "pinned": False,
                "endorsed": False,
                "unread_comments_count": 0,
                "read": False,
                "comments_count": 0
            })
        url = reverse('un_flag_abuse_for_thread',
                      kwargs={
                          'thread_id': '518d4237b023791dca00000d',
                          'course_id': self.course_id.to_deprecated_string()
                      })
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (('get', '{prefix}/threads/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'mark_as_read': True,
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                }),
            (('put',
              '{prefix}/threads/518d4237b023791dca00000d/abuse_unflag'.format(
                  prefix=CS_PREFIX)), {
                      'data': {
                          'user_id': '1'
                      },
                      'params': {
                          'request_id': ANY
                      },
                      'headers': ANY,
                      'timeout': 5
                  }),
            (('get', '{prefix}/threads/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'mark_as_read': True,
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                })
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_flag_comment_open(self, mock_request):
        self.flag_comment(mock_request, False)

    def test_flag_comment_close(self, mock_request):
        self.flag_comment(mock_request, True)

    def flag_comment(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(
            mock_request, {
                "body": "this is a comment",
                "course_id": "MITx/999/Robot_Super_Course",
                "anonymous": False,
                "anonymous_to_peers": False,
                "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
                "created_at": "2013-05-10T18:53:43Z",
                "updated_at": "2013-05-10T18:53:43Z",
                "at_position_list": [],
                "closed": is_closed,
                "id": "518d4237b023791dca00000d",
                "user_id": "1",
                "username": "******",
                "votes": {
                    "count": 0,
                    "up_count": 0,
                    "down_count": 0,
                    "point": 0
                },
                "abuse_flaggers": [1],
                "type": "comment",
                "endorsed": False
            })
        url = reverse('flag_abuse_for_comment',
                      kwargs={
                          'comment_id': '518d4237b023791dca00000d',
                          'course_id': self.course_id.to_deprecated_string()
                      })
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (('get', '{prefix}/comments/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                }),
            (('put',
              '{prefix}/comments/518d4237b023791dca00000d/abuse_flag'.format(
                  prefix=CS_PREFIX)), {
                      'data': {
                          'user_id': '1'
                      },
                      'params': {
                          'request_id': ANY
                      },
                      'headers': ANY,
                      'timeout': 5
                  }),
            (('get', '{prefix}/comments/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                })
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_un_flag_comment_open(self, mock_request):
        self.un_flag_comment(mock_request, False)

    def test_un_flag_comment_close(self, mock_request):
        self.un_flag_comment(mock_request, True)

    def un_flag_comment(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(
            mock_request, {
                "body": "this is a comment",
                "course_id": "MITx/999/Robot_Super_Course",
                "anonymous": False,
                "anonymous_to_peers": False,
                "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
                "created_at": "2013-05-10T18:53:43Z",
                "updated_at": "2013-05-10T18:53:43Z",
                "at_position_list": [],
                "closed": is_closed,
                "id": "518d4237b023791dca00000d",
                "user_id": "1",
                "username": "******",
                "votes": {
                    "count": 0,
                    "up_count": 0,
                    "down_count": 0,
                    "point": 0
                },
                "abuse_flaggers": [],
                "type": "comment",
                "endorsed": False
            })
        url = reverse('un_flag_abuse_for_comment',
                      kwargs={
                          'comment_id': '518d4237b023791dca00000d',
                          'course_id': self.course_id.to_deprecated_string()
                      })
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (('get', '{prefix}/comments/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                }),
            (('put',
              '{prefix}/comments/518d4237b023791dca00000d/abuse_unflag'.format(
                  prefix=CS_PREFIX)), {
                      'data': {
                          'user_id': '1'
                      },
                      'params': {
                          'request_id': ANY
                      },
                      'headers': ANY,
                      'timeout': 5
                  }),
            (('get', '{prefix}/comments/518d4237b023791dca00000d'.format(
                prefix=CS_PREFIX)), {
                    'data': None,
                    'params': {
                        'request_id': ANY
                    },
                    'headers': ANY,
                    'timeout': 5
                })
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)
Exemple #32
0
class TestSIPArrange(TestCase):

    fixture_files = ['test_user.json', 'sip_arrange.json']
    fixtures = [os.path.join(THIS_DIR, 'fixtures', p) for p in fixture_files]

    def setUp(self):
        self.client = Client()
        self.client.login(username='******', password='******')

    def test_fixtures(self):
        objs = models.SIPArrange.objects.all()
        assert len(objs) > 0

    def test_arrange_contents_data_no_path(self):
        # Call endpoint
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': None},
            follow=True)
        # Verify
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert 'directories' in response_dict
        assert base64.b64encode("newsip") in response_dict['directories']
        assert base64.b64encode("toplevel") in response_dict['directories']
        assert len(response_dict['directories']) == 2
        assert 'entries' in response_dict
        assert base64.b64encode("newsip") in response_dict['entries']
        assert base64.b64encode("toplevel") in response_dict['entries']
        assert len(response_dict['entries']) == 2
        assert 'properties' in response_dict
        assert base64.b64encode("newsip") in response_dict['properties']
        assert response_dict['properties'][base64.b64encode(
            "newsip")]['display_string'] == '2 objects'
        assert base64.b64encode("toplevel") in response_dict['properties']
        assert response_dict['properties'][base64.b64encode(
            "toplevel")]['display_string'] == '1 objects'
        assert len(response_dict) == 3

    def test_arrange_contents_data_path(self):
        # Folder, without /
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange/newsip/objects/')},
            follow=True)
        # Verify
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert 'directories' in response_dict
        assert base64.b64encode(
            "evelyn_s_second_photo") in response_dict['directories']
        assert len(response_dict['directories']) == 1
        assert 'entries' in response_dict
        assert base64.b64encode(
            "evelyn_s_photo.jpg") in response_dict['entries']
        assert base64.b64encode(
            "evelyn_s_second_photo") in response_dict['entries']
        assert len(response_dict['entries']) == 2
        assert 'properties' in response_dict
        assert base64.b64encode(
            "evelyn_s_second_photo") in response_dict['properties']
        assert response_dict['properties'][base64.b64encode(
            "evelyn_s_second_photo")]['display_string'] == '1 objects'
        assert len(response_dict) == 3

    def test_delete_arranged_files(self):
        # Check to-be-deleted exists
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange')},
            follow=True)
        assert base64.b64encode('newsip') in json.loads(
            response.content)['directories']
        # Delete files
        response = self.client.post(
            reverse('components.filesystem_ajax.views.delete_arrange'),
            data={'filepath': base64.b64encode('/arrange/newsip/')},
            follow=True)
        assert response.status_code == 200
        assert json.loads(response.content) == {
            'message': 'Delete successful.'
        }
        # Check deleted
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange')},
            follow=True)
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert base64.b64encode("toplevel") in response_dict['directories']
        assert len(response_dict['directories']) == 1
        assert base64.b64encode("toplevel") in response_dict['entries']
        assert len(response_dict['entries']) == 1

    def test_create_arranged_directory(self):
        # Verify does not exist already
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange')},
            follow=True)
        assert base64.b64encode('new_dir') not in json.loads(
            response.content)['directories']
        assert base64.b64encode('new_dir') not in json.loads(
            response.content)['entries']
        # Create directory
        response = self.client.post(reverse(
            'components.filesystem_ajax.views.create_directory_within_arrange'
        ),
                                    data={
                                        'path':
                                        base64.b64encode('/arrange/new_dir')
                                    },
                                    follow=True)
        assert response.status_code == 200
        assert json.loads(response.content) == {
            'message': 'Creation successful.'
        }
        # Check created
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange')},
            follow=True)
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert base64.b64encode('new_dir') in response_dict['directories']
        assert base64.b64encode('newsip') in response_dict['directories']
        assert base64.b64encode('toplevel') in response_dict['directories']
        assert len(response_dict['directories']) == 3
        assert base64.b64encode('new_dir') in response_dict['entries']
        assert base64.b64encode('newsip') in response_dict['entries']
        assert base64.b64encode('toplevel') in response_dict['entries']
        assert len(response_dict['entries']) == 3

    def test_move_within_arrange(self):
        # Move directory
        response = self.client.post(
            reverse('components.filesystem_ajax.views.move_within_arrange'),
            data={
                'filepath': base64.b64encode('/arrange/newsip/'),
                'destination': base64.b64encode('/arrange/toplevel/')
            },
            follow=True)
        assert response.status_code == 200
        assert json.loads(response.content) == {
            'message': 'SIP files successfully moved.'
        }
        # Check gone from parent
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange')},
            follow=True)
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert base64.b64encode('toplevel') in response_dict['directories']
        assert base64.b64encode('newsip') not in response_dict['directories']
        assert len(response_dict['directories']) == 1
        assert base64.b64encode('toplevel') in response_dict['entries']
        assert base64.b64encode('newsip') not in response_dict['entries']
        assert len(response_dict['entries']) == 1

        # Check now in subdirectory
        response = self.client.get(
            reverse('components.filesystem_ajax.views.arrange_contents'),
            {'path': base64.b64encode('/arrange/toplevel')},
            follow=True)
        assert response.status_code == 200
        response_dict = json.loads(response.content)
        assert base64.b64encode('subsip') in response_dict['directories']
        assert base64.b64encode('newsip') in response_dict['directories']
        assert len(response_dict['directories']) == 2
        assert base64.b64encode('subsip') in response_dict['entries']
        assert base64.b64encode('newsip') in response_dict['entries']
        assert len(response_dict['entries']) == 2
Exemple #33
0
class MessagingApiTest(TestCase):
    "Messaging functional tests for api"

    username = "******"
    password = "******"
    prepared = False
    authentication_headers = {
        "CONTENT_TYPE": "application/json",
        "HTTP_AUTHORIZATION": "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk"
    }
    content_type = 'application/json'

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.user_contact = Contact(name='test',
                                        related_user=self.user.get_profile(),
                                        contact_type=self.contact_type)
            self.user_contact.set_user(self.user)
            self.user_contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.mlist = MailingList(name='test', from_contact=self.contact)
            self.mlist.set_default_user()
            self.mlist.save()

            self.message = Message(title='test',
                                   body='test',
                                   author=self.contact,
                                   stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True

    def test_unauthenticated_access(self):
        "Test index page at /api/messaging/mlist"
        response = self.client.get('/api/messaging/mlist')
        # Redirects as unauthenticated
        self.assertEquals(response.status_code, 401)

    def test_get_mlist(self):
        """ Test index page api/messaging/mlist """
        response = self.client.get(path=reverse('api_messaging_mlist'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_one_mlist(self):
        response = self.client.get(path=reverse(
            'api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_mlist(self):
        updates = {
            "name": "API mailing list",
            "description": "API description update",
            "from_contact": self.contact.id,
            "members": [
                self.contact.id,
            ]
        }
        response = self.client.put(path=reverse(
            'api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])
        self.assertEquals(data['description'], updates['description'])
        self.assertEquals(data['from_contact']['id'], updates['from_contact'])
        for i, member in enumerate(data['members']):
            self.assertEquals(member['id'], updates['members'][i])

    def test_get_streams(self):
        """ Test index page api/messaging/streams """
        response = self.client.get(path=reverse('api_messaging_streams'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_stream(self):
        response = self.client.get(path=reverse(
            'api_messaging_streams', kwargs={'object_ptr': self.stream.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_stream(self):
        updates = {
            "name": "API stream",
        }
        response = self.client.put(path=reverse(
            'api_messaging_streams', kwargs={'object_ptr': self.stream.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])

    def test_get_messages(self):
        """ Test index page api/messaging/messages """
        response = self.client.get(path=reverse('api_messaging_messages'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_message(self):
        response = self.client.get(path=reverse(
            'api_messaging_messages', kwargs={'object_ptr': self.message.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_send_message(self):
        updates = {
            "title": "API message title",
            "body": "Test body",
            "stream": self.stream.id,
            "multicomplete_recipients": u'*****@*****.**'
        }
        response = self.client.post(path=reverse('api_messaging_messages'),
                                    content_type=self.content_type,
                                    data=json.dumps(updates),
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])

    def test_reply_to_message(self):
        updates = {
            "title": "API test",
            "body": "Test body",
            "stream": self.stream.id,
            "multicomplete_recipients": u'*****@*****.**'
        }
        response = self.client.put(path=reverse(
            'api_messaging_messages', kwargs={'object_ptr': self.message.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertNotEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])
Exemple #34
0
class TestProjectViews(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create(username="******")
        self.u.set_password("test")
        self.u.save()
        self.c.login(username="******", password="******")
        self.pu = PMTUser.objects.create(username="******",
                                         email="*****@*****.**",
                                         status="active")
        Claim.objects.create(django_user=self.u, pmt_user=self.pu)

    def test_all_projects_page(self):
        p = ProjectFactory()
        r = self.c.get("/project/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(p.name in r.content)
        self.assertTrue(p.get_absolute_url() in r.content)

    def test_project_page(self):
        p = ProjectFactory()
        r = self.c.get(p.get_absolute_url())
        self.assertEqual(r.status_code, 200)
        self.assertTrue(p.name in r.content)

    def test_add_node(self):
        p = ProjectFactory()
        r = self.c.post(
            p.get_absolute_url() + "add_node/",
            dict(subject='node subject', body="this is the body"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(p.get_absolute_url())
        self.assertTrue("node subject" in r.content)
        self.assertTrue("this is the body" in r.content)

    def test_add_node_with_tags(self):
        p = ProjectFactory()
        r = self.c.post(
            p.get_absolute_url() + "add_node/",
            dict(subject='node subject', body="this is the body",
                 tags="tagone, tagtwo"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(p.get_absolute_url())
        self.assertTrue("node subject" in r.content)
        self.assertTrue("this is the body" in r.content)

    def test_add_node_empty_body(self):
        p = ProjectFactory()
        r = self.c.post(
            p.get_absolute_url() + "add_node/",
            dict(subject='node subject', body=""))
        self.assertEqual(r.status_code, 302)

    def test_add_status_update(self):
        p = ProjectFactory()
        r = self.c.post(
            p.get_absolute_url() + "add_update/",
            dict(body="xyzzy"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(p.get_absolute_url())
        self.assertTrue("xyzzy" in r.content)

        r = self.c.get(self.pu.get_absolute_url())
        self.assertTrue("xyzzy" in r.content)

        r = self.c.get("/status/")
        self.assertTrue("xyzzy" in r.content)

    def test_add_status_empty_body(self):
        p = ProjectFactory()
        r = self.c.post(
            p.get_absolute_url() + "add_update/",
            dict(body=""))
        self.assertEqual(r.status_code, 302)

    def test_edit_statusupdate(self):
        s = StatusUpdateFactory()
        r = self.c.post(
            s.get_absolute_url(),
            dict(body="xyzzy"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(s.get_absolute_url())
        self.assertTrue("xyzzy" in r.content)

    def test_remove_user(self):
        p = ProjectFactory()
        u = UserFactory()
        p.add_manager(u)
        r = self.c.get(p.get_absolute_url() + "remove_user/%s/" % u.username)
        self.assertTrue(u.fullname in r.content)
        self.assertTrue(u in p.managers())
        self.c.post(p.get_absolute_url() + "remove_user/%s/" % u.username)
        self.assertTrue(u not in p.managers())

    def test_add_user(self):
        p = ProjectFactory()
        u = UserFactory(status='active')
        r = self.c.post(p.get_absolute_url() + "add_user/",
                        dict(username=u.username))
        self.assertEqual(r.status_code, 302)
        self.assertTrue(u in p.all_personnel_in_project())

    def test_add_milestone(self):
        p = ProjectFactory()
        r = self.c.post(p.get_absolute_url() + "add_milestone/",
                        dict(name="NEW TEST MILESTONE",
                             target_date="2020-01-01"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(p.get_absolute_url())
        self.assertTrue("NEW TEST MILESTONE" in r.content)
Exemple #35
0
class TestItemWorkflow(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create(username="******")
        self.u.set_password("test")
        self.u.save()
        self.c.login(username="******", password="******")
        self.pu = PMTUser.objects.create(username="******",
                                         email="*****@*****.**",
                                         status="active")
        Claim.objects.create(django_user=self.u, pmt_user=self.pu)

    def test_add_comment(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "comment/",
            dict(comment='this is a comment'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)

    def test_add_comment_empty(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "comment/",
            dict(comment=''))
        self.assertEqual(r.status_code, 302)

    def test_resolve(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "resolve/",
            dict(comment='this is a comment',
                 r_status='FIXED'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("RESOLVED" in r.content)
        self.assertTrue("FIXED" in r.content)

    def test_resolve_with_time(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "resolve/",
            dict(comment='this is a comment',
                 time='2.5 hours',
                 r_status='FIXED'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("RESOLVED" in r.content)
        self.assertTrue("FIXED" in r.content)
        self.assertTrue("2:30:00" in r.content)

    def test_resolve_self_assigned(self):
        i = ItemFactory(owner=self.pu, assigned_to=self.pu)
        r = self.c.post(
            i.get_absolute_url() + "resolve/",
            dict(comment='this is a comment',
                 r_status='FIXED'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("VERIFIED" in r.content)

    def test_inprogress(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "inprogress/",
            dict(comment='this is a comment'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("INPROGRESS" in r.content)

    def test_verify(self):
        i = ItemFactory(status='RESOLVED', r_status='FIXED')
        r = self.c.post(
            i.get_absolute_url() + "verify/",
            dict(comment='this is a comment'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("VERIFIED" in r.content)

    def test_reopen(self):
        i = ItemFactory(status='RESOLVED', r_status='FIXED')
        r = self.c.post(
            i.get_absolute_url() + "reopen/",
            dict(comment='this is a comment'))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("this is a comment" in r.content)
        self.assertTrue("OPEN" in r.content)

    def test_split(self):
        i = ItemFactory()
        cnt = Item.objects.all().count()
        r = self.c.post(
            i.get_absolute_url() + "split/",
            dict(title_0="sub item one",
                 title_1="sub item two",
                 title_2="sub item three"))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("VERIFIED" in r.content)
        self.assertTrue("Split" in r.content)
        self.assertTrue("sub item two" in r.content)
        # make sure there are three more items now
        self.assertEqual(Item.objects.all().count(), cnt + 3)

    def test_split_bad_params(self):
        i = ItemFactory()
        r = self.c.post(
            i.get_absolute_url() + "split/",
            dict(title_0="",
                 other_param="sub item two"))
        self.assertEqual(r.status_code, 302)

    def test_add_todos(self):
        i = ItemFactory()
        project = i.milestone.project
        r = self.c.post(
            project.get_absolute_url() + "add_todo/",
            dict(title_0="this is a todo",
                 tags="one two"))
        self.assertEqual(r.status_code, 302)

        r = self.c.get(project.get_absolute_url())
        self.assertTrue("this is a todo" in r.content)

    def test_add_todos_bad_params(self):
        i = ItemFactory()
        project = i.milestone.project
        r = self.c.post(
            project.get_absolute_url() + "add_todo/",
            dict(title_0="this is a todo",
                 some_other_param="foo",
                 title_1=""))
        self.assertEqual(r.status_code, 302)

    def test_add_bug(self):
        i = ItemFactory()
        project = i.milestone.project
        r = self.c.post(
            project.get_absolute_url() + "add_bug/",
            dict(title='test bug', description='test',
                 priority='1', milestone=i.milestone.mid,
                 owner=i.owner.username,
                 assigned_to=i.assigned_to.username,
                 tags="tagone, tagtwo"))
        r = self.c.get(project.get_absolute_url())
        self.assertTrue("test bug" in r.content)

    def test_add_bug_no_tags(self):
        i = ItemFactory()
        project = i.milestone.project
        r = self.c.post(
            project.get_absolute_url() + "add_bug/",
            dict(title='test bug', description='test',
                 priority='1', milestone=i.milestone.mid,
                 owner=i.owner.username,
                 assigned_to=i.assigned_to.username,
                 tags=""))
        r = self.c.get(project.get_absolute_url())
        self.assertTrue("test bug" in r.content)

    def test_change_priority(self):
        i = ItemFactory()
        r = self.c.get(i.get_absolute_url() + "priority/4/")
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue("CRITICAL" in r.content)

    def test_reassign(self):
        i = ItemFactory()
        u = UserFactory()
        r = self.c.post(i.get_absolute_url() + "assigned_to/",
                        dict(assigned_to=u.username))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue(u.fullname in r.content)

    def test_change_owner(self):
        i = ItemFactory()
        u = UserFactory()
        r = self.c.post(i.get_absolute_url() + "owner/",
                        dict(owner=u.username))
        self.assertEqual(r.status_code, 302)
        r = self.c.get(i.get_absolute_url())
        self.assertTrue(u.fullname in r.content)
Exemple #36
0
class BadgerApiViewsTests(BadgerTestCase):
    def setUp(self):
        self.client = Client()

        self.testuser = self._get_user()

        self.badge = Badge(creator=self.testuser,
                           title="Test II",
                           description="Another test",
                           unique=True)
        self.badge.save()

        self.awards_url = reverse('badger.views.awards_list',
                                  args=(self.badge.slug, ))

        key = Key()
        key.user = self.testuser
        self.password = key.generate_secret()
        self.username = key.key
        key.save()
        self.key = key

        auth_ct = '%s:%s' % (self.username, self.password)
        self.basic_auth = 'Basic %s' % b64encode(auth_ct)
        self.headers = {'HTTP_AUTHORIZATION': self.basic_auth}

        Award.objects.all().delete()

    def tearDown(self):
        self.key.delete()
        Award.objects.all().delete()
        Badge.objects.all().delete()

    def test_forbidden_without_key(self):
        """POST should require a valid key, or else yield a 403 response"""
        resp = self.client.get(self.awards_url)
        ok_(200, resp.status_code)

        resp = self.client.post(self.awards_url)
        ok_(403, resp.status_code)

        resp = self.client.post(self.awards_url,
                                {'HTTP_AUTHORIZATION': 'Basic THISISINVALID'})
        ok_(403, resp.status_code)

        resp = self.client.post(self.awards_url, self.headers)
        ok_(200, resp.status_code)

        resp = self.client.get(self.awards_url, self.headers)
        ok_(200, resp.status_code)

    def test_bad_data(self):
        """Bad JSON request should result in a 400 response"""
        resp = self.client.post(self.awards_url,
                                "THISISBADDATA",
                                content_type='application/json',
                                HTTP_AUTHORIZATION=self.basic_auth)
        ok_(400, resp.status_code)

    def test_badge_award(self):
        """Can award badges from API"""
        invite_email = '*****@*****.**'
        invalid_email = 'THISISINVALID'
        description = "Is a hoopy frood."
        award_user = self._get_user(username="******",
                                    email="*****@*****.**")

        # Construct the request data...
        data = dict(
            description=description,
            emails=[
                award_user.email,
                invite_email,
                invalid_email,
            ],
        )

        # POST to the awards URL
        resp = self.client.post(self.awards_url,
                                json.dumps(data),
                                content_type='application/json',
                                HTTP_AUTHORIZATION=self.basic_auth)

        ok_(self.badge.is_awarded_to(award_user))
        award = Award.objects.get(user=award_user, badge=self.badge)
        eq_(description, award.description)

        eq_('application/json', resp['Content-Type'])
        data = json.loads(resp.content)

        ok_('successes' in data)
        ok_(award_user.email in data['successes'])
        eq_('AWARDED', data['successes'][award_user.email])
        ok_(invite_email in data['successes'])
        eq_('INVITED', data['successes'][invite_email])

        ok_('errors' in data)
        ok_(invalid_email in data['errors'])
        eq_('INVALID', data['errors'][invalid_email])

    def test_no_description(self):
        """Awards can be issued with no description"""
        award_user = self._get_user(username="******",
                                    email="*****@*****.**")

        data = {"emails": [award_user.email]}

        resp = self.client.post(self.awards_url,
                                json.dumps(data),
                                content_type='application/json',
                                HTTP_AUTHORIZATION=self.basic_auth)

        eq_('application/json', resp['Content-Type'])
        data = json.loads(resp.content)

        ok_(award_user.email in data['successes'])
        ok_(award_user.email not in data['errors'])
        ok_(self.badge.is_awarded_to(award_user))

    def test_already_awarded(self):
        """Can award badges from API"""
        description = "Is a hoopy frood."
        invite_email = '*****@*****.**'
        award_user = self._get_user(username="******",
                                    email="*****@*****.**")

        award = self.badge.award_to(email=award_user.email)
        deferred_award = self.badge.award_to(email=invite_email)

        # Construct the request data...
        data = dict(
            description=description,
            emails=[
                invite_email,
                award_user.email,
            ],
        )

        # POST to the awards URL
        resp = self.client.post(self.awards_url,
                                json.dumps(data),
                                content_type='application/json',
                                HTTP_AUTHORIZATION=self.basic_auth)

        eq_('application/json', resp['Content-Type'])
        data = json.loads(resp.content)

        print "DATA %s" % data

        ok_('errors' in data)
        ok_(award_user.email in data['errors'])
        eq_('ALREADYAWARDED', data['errors'][award_user.email])
        ok_(invite_email in data['errors'])
        eq_('ALREADYAWARDED', data['errors'][invite_email])

    def test_disallowed_badge_award(self):
        """User should not be able to POST an award to a badge for which the
        user hasn't got permission to do so"""
        user = self._get_user(username="******", email="*****@*****.**")
        badge = Badge(creator=user,
                      title="Hey you badge",
                      description="Another test",
                      unique=True)
        badge.save()

        awards_url = reverse('badger.views.awards_list',
                             args=(self.badge.slug, ))

        data = dict(emails=[
            '*****@*****.**',
        ])

        resp = self.client.post(awards_url,
                                json.dumps(data),
                                content_type='application/json',
                                HTTP_AUTHORIZATION=self.basic_auth)

        ok_(403, resp.status_code)
Exemple #37
0
class LoginTest(CacheIsolationTestCase):
    """
    Test login_user() view
    """

    ENABLED_CACHES = ['default']
    LOGIN_FAILED_WARNING = 'Email or password is incorrect'
    ACTIVATE_ACCOUNT_WARNING = 'In order to sign in, you need to activate your account'
    username = '******'
    user_email = '*****@*****.**'
    password = '******'

    def setUp(self):
        """Setup a test user along with its registration and profile"""
        super(LoginTest, self).setUp()
        self.user = UserFactory.build(username=self.username, email=self.user_email)
        self.user.set_password(self.password)
        self.user.save()

        RegistrationFactory(user=self.user)
        UserProfileFactory(user=self.user)

        self.client = Client()
        cache.clear()

        try:
            self.url = reverse('login_post')
        except NoReverseMatch:
            self.url = reverse('login')

    def test_login_success(self):
        response, mock_audit_log = self._login_response(
            self.user_email, self.password, patched_audit_log='student.models.AUDIT_LOG'
        )
        self._assert_response(response, success=True)
        self._assert_audit_log(mock_audit_log, 'info', [u'Login success', self.user_email])

    @patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
    def test_login_success_no_pii(self):
        response, mock_audit_log = self._login_response(
            self.user_email, self.password, patched_audit_log='student.models.AUDIT_LOG'
        )
        self._assert_response(response, success=True)
        self._assert_audit_log(mock_audit_log, 'info', [u'Login success'])
        self._assert_not_in_audit_log(mock_audit_log, 'info', [self.user_email])

    def test_login_success_unicode_email(self):
        unicode_email = u'test' + six.unichr(40960) + u'@edx.org'
        self.user.email = unicode_email
        self.user.save()

        response, mock_audit_log = self._login_response(
            unicode_email, self.password, patched_audit_log='student.models.AUDIT_LOG'
        )
        self._assert_response(response, success=True)
        self._assert_audit_log(mock_audit_log, 'info', [u'Login success', unicode_email])

    def test_last_login_updated(self):
        old_last_login = self.user.last_login
        self.test_login_success()
        self.user.refresh_from_db()
        assert self.user.last_login > old_last_login

    def test_login_success_prevent_auth_user_writes(self):
        with waffle().override(PREVENT_AUTH_USER_WRITES, True):
            old_last_login = self.user.last_login
            self.test_login_success()
            self.user.refresh_from_db()
            assert old_last_login == self.user.last_login

    def test_login_fail_no_user_exists(self):
        nonexistent_email = u'*****@*****.**'
        response, mock_audit_log = self._login_response(
            nonexistent_email,
            self.password,
        )
        self._assert_response(response, success=False, value=self.LOGIN_FAILED_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Unknown user email', nonexistent_email])

    @patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
    def test_login_fail_no_user_exists_no_pii(self):
        nonexistent_email = u'*****@*****.**'
        response, mock_audit_log = self._login_response(
            nonexistent_email,
            self.password,
        )
        self._assert_response(response, success=False, value=self.LOGIN_FAILED_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Unknown user email'])
        self._assert_not_in_audit_log(mock_audit_log, 'warning', [nonexistent_email])

    def test_login_fail_wrong_password(self):
        response, mock_audit_log = self._login_response(
            self.user_email,
            'wrong_password',
        )
        self._assert_response(response, success=False, value=self.LOGIN_FAILED_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning',
                               [u'Login failed', u'password for', self.user_email, u'invalid'])

    @patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
    def test_login_fail_wrong_password_no_pii(self):
        response, mock_audit_log = self._login_response(self.user_email, 'wrong_password')
        self._assert_response(response, success=False, value=self.LOGIN_FAILED_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'password for', u'invalid'])
        self._assert_not_in_audit_log(mock_audit_log, 'warning', [self.user_email])

    @patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
    def test_login_not_activated_no_pii(self):
        # De-activate the user
        self.user.is_active = False
        self.user.save()

        # Should now be unable to login
        response, mock_audit_log = self._login_response(
            self.user_email,
            self.password
        )
        self._assert_response(response, success=False,
                              value="In order to sign in, you need to activate your account.")
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Account not active for user'])
        self._assert_not_in_audit_log(mock_audit_log, 'warning', [u'test'])

    def test_login_not_activated_with_correct_credentials(self):
        """
        Tests that when user login with the correct credentials but with an inactive
        account, the system, send account activation email notification to the user.
        """
        self.user.is_active = False
        self.user.save()

        response, mock_audit_log = self._login_response(
            self.user_email,
            self.password,
        )
        self._assert_response(response, success=False, value=self.ACTIVATE_ACCOUNT_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Account not active for user'])

    @patch('openedx.core.djangoapps.user_authn.views.login._log_and_raise_inactive_user_auth_error')
    def test_login_inactivated_user_with_incorrect_credentials(self, mock_inactive_user_email_and_error):
        """
        Tests that when user login with incorrect credentials and an inactive account,
        the system does *not* send account activation email notification to the user.
        """
        nonexistent_email = '*****@*****.**'
        self.user.is_active = False
        self.user.save()
        response, mock_audit_log = self._login_response(nonexistent_email, 'incorrect_password')

        self.assertFalse(mock_inactive_user_email_and_error.called)
        self._assert_response(response, success=False, value=self.LOGIN_FAILED_WARNING)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', u'Unknown user email', nonexistent_email])

    def test_login_unicode_email(self):
        unicode_email = self.user_email + six.unichr(40960)
        response, mock_audit_log = self._login_response(
            unicode_email,
            self.password,
        )
        self._assert_response(response, success=False)
        self._assert_audit_log(mock_audit_log, 'warning', [u'Login failed', unicode_email])

    def test_login_unicode_password(self):
        unicode_password = self.password + six.unichr(1972)
        response, mock_audit_log = self._login_response(
            self.user_email,
            unicode_password,
        )
        self._assert_response(response, success=False)
        self._assert_audit_log(mock_audit_log, 'warning',
                               [u'Login failed', u'password for', self.user_email, u'invalid'])

    def test_logout_logging(self):
        response, _ = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)
        logout_url = reverse('logout')
        with patch('student.models.AUDIT_LOG') as mock_audit_log:
            response = self.client.post(logout_url)
        self.assertEqual(response.status_code, 200)
        self._assert_audit_log(mock_audit_log, 'info', [u'Logout', u'test'])

    def test_login_user_info_cookie(self):
        response, _ = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)

        # Verify the format of the "user info" cookie set on login
        cookie = self.client.cookies[settings.EDXMKTG_USER_INFO_COOKIE_NAME]
        user_info = json.loads(cookie.value)

        self.assertEqual(user_info["version"], settings.EDXMKTG_USER_INFO_COOKIE_VERSION)
        self.assertEqual(user_info["username"], self.user.username)

        # Check that the URLs are absolute
        for url in user_info["header_urls"].values():
            self.assertIn("http://testserver/", url)

    def test_logout_deletes_mktg_cookies(self):
        response, _ = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)

        # Check that the marketing site cookies have been set
        self.assertIn(settings.EDXMKTG_LOGGED_IN_COOKIE_NAME, self.client.cookies)
        self.assertIn(settings.EDXMKTG_USER_INFO_COOKIE_NAME, self.client.cookies)

        # Log out
        logout_url = reverse('logout')
        response = self.client.post(logout_url)

        # Check that the marketing site cookies have been deleted
        # (cookies are deleted by setting an expiration date in 1970)
        for cookie_name in [settings.EDXMKTG_LOGGED_IN_COOKIE_NAME, settings.EDXMKTG_USER_INFO_COOKIE_NAME]:
            cookie = self.client.cookies[cookie_name]
            self.assertIn("01-Jan-1970", cookie.get('expires'))

    @override_settings(
        EDXMKTG_LOGGED_IN_COOKIE_NAME=u"unicode-logged-in",
        EDXMKTG_USER_INFO_COOKIE_NAME=u"unicode-user-info",
    )
    def test_unicode_mktg_cookie_names(self):
        # When logged in cookie names are loaded from JSON files, they may
        # have type `unicode` instead of `str`, which can cause errors
        # when calling Django cookie manipulation functions.
        response, _ = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)

        response = self.client.post(reverse('logout'))
        expected = {
            'target': '/',
        }
        self.assertDictContainsSubset(expected, response.context_data)

    @patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
    def test_logout_logging_no_pii(self):
        response, _ = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)
        logout_url = reverse('logout')
        with patch('student.models.AUDIT_LOG') as mock_audit_log:
            response = self.client.post(logout_url)
        self.assertEqual(response.status_code, 200)
        self._assert_audit_log(mock_audit_log, 'info', [u'Logout'])
        self._assert_not_in_audit_log(mock_audit_log, 'info', [u'test'])

    def test_login_ratelimited_success(self):
        # Try (and fail) logging in with fewer attempts than the limit of 30
        # and verify that you can still successfully log in afterwards.
        for i in range(20):
            password = u'test_password{0}'.format(i)
            response, _audit_log = self._login_response(self.user_email, password)
            self._assert_response(response, success=False)
        # now try logging in with a valid password
        response, _audit_log = self._login_response(self.user_email, self.password)
        self._assert_response(response, success=True)

    def test_login_ratelimited(self):
        # try logging in 30 times, the default limit in the number of failed
        # login attempts in one 5 minute period before the rate gets limited
        for i in range(30):
            password = u'test_password{0}'.format(i)
            self._login_response(self.user_email, password)
        # check to see if this response indicates that this was ratelimited
        response, _audit_log = self._login_response(self.user_email, 'wrong_password')
        self._assert_response(response, success=False, value='Too many failed login attempts')

    @patch.dict("django.conf.settings.FEATURES", {"DISABLE_SET_JWT_COOKIES_FOR_TESTS": False})
    def test_login_refresh(self):
        def _assert_jwt_cookie_present(response):
            self.assertEqual(response.status_code, 200)
            self.assertIn(jwt_cookies.jwt_cookie_header_payload_name(), self.client.cookies)

        setup_login_oauth_client()
        response, _ = self._login_response(self.user_email, self.password)
        _assert_jwt_cookie_present(response)

        response = self.client.post(reverse('login_refresh'))
        _assert_jwt_cookie_present(response)

    @patch.dict("django.conf.settings.FEATURES", {"DISABLE_SET_JWT_COOKIES_FOR_TESTS": False})
    def test_login_refresh_anonymous_user(self):
        response = self.client.post(reverse('login_refresh'))
        self.assertEqual(response.status_code, 401)
        self.assertNotIn(jwt_cookies.jwt_cookie_header_payload_name(), self.client.cookies)

    @patch.dict("django.conf.settings.FEATURES", {'PREVENT_CONCURRENT_LOGINS': True})
    def test_single_session(self):
        creds = {'email': self.user_email, 'password': self.password}
        client1 = Client()
        client2 = Client()

        response = client1.post(self.url, creds)
        self._assert_response(response, success=True)

        # Reload the user from the database
        self.user = User.objects.get(pk=self.user.pk)

        self.assertEqual(self.user.profile.get_meta()['session_id'], client1.session.session_key)

        # second login should log out the first
        response = client2.post(self.url, creds)
        self._assert_response(response, success=True)

        try:
            # this test can be run with either lms or studio settings
            # since studio does not have a dashboard url, we should
            # look for another url that is login_required, in that case
            url = reverse('dashboard')
        except NoReverseMatch:
            url = reverse('upload_transcripts')
        response = client1.get(url)
        # client1 will be logged out
        self.assertEqual(response.status_code, 302)

    @patch.dict("django.conf.settings.FEATURES", {'PREVENT_CONCURRENT_LOGINS': True})
    def test_single_session_with_no_user_profile(self):
        """
        Assert that user login with cas (Central Authentication Service) is
        redirect to dashboard in case of lms or upload_transcripts in case of
        cms
        """
        user = UserFactory.build(username='******', email='*****@*****.**')
        user.set_password(self.password)
        user.save()

        # Assert that no profile is created.
        self.assertFalse(hasattr(user, 'profile'))

        creds = {'email': '*****@*****.**', 'password': self.password}
        client1 = Client()
        client2 = Client()

        response = client1.post(self.url, creds)
        self._assert_response(response, success=True)

        # Reload the user from the database
        user = User.objects.get(pk=user.pk)

        # Assert that profile is created.
        self.assertTrue(hasattr(user, 'profile'))

        # second login should log out the first
        response = client2.post(self.url, creds)
        self._assert_response(response, success=True)

        try:
            # this test can be run with either lms or studio settings
            # since studio does not have a dashboard url, we should
            # look for another url that is login_required, in that case
            url = reverse('dashboard')
        except NoReverseMatch:
            url = reverse('upload_transcripts')
        response = client1.get(url)
        # client1 will be logged out
        self.assertEqual(response.status_code, 302)

    @patch.dict("django.conf.settings.FEATURES", {'PREVENT_CONCURRENT_LOGINS': True})
    def test_single_session_with_url_not_having_login_required_decorator(self):
        # accessing logout url as it does not have login-required decorator it will avoid redirect
        # and go inside the enforce_single_login

        creds = {'email': self.user_email, 'password': self.password}
        client1 = Client()
        client2 = Client()

        response = client1.post(self.url, creds)
        self._assert_response(response, success=True)

        # Reload the user from the database
        self.user = User.objects.get(pk=self.user.pk)

        self.assertEqual(self.user.profile.get_meta()['session_id'], client1.session.session_key)

        # second login should log out the first
        response = client2.post(self.url, creds)
        self._assert_response(response, success=True)

        url = reverse('logout')

        response = client1.get(url)
        self.assertEqual(response.status_code, 200)

    def test_change_enrollment_400(self):
        """
        Tests that a 400 in change_enrollment doesn't lead to a 404
        and in fact just logs in the user without incident
        """
        # add this post param to trigger a call to change_enrollment
        extra_post_params = {"enrollment_action": "enroll"}
        with patch('student.views.change_enrollment') as mock_change_enrollment:
            mock_change_enrollment.return_value = HttpResponseBadRequest("I am a 400")
            response, _ = self._login_response(
                self.user_email, self.password, extra_post_params=extra_post_params,
            )
        response_content = json.loads(response.content.decode('utf-8'))
        self.assertIsNone(response_content["redirect_url"])
        self._assert_response(response, success=True)

    def test_change_enrollment_200_no_redirect(self):
        """
        Tests "redirect_url" is None if change_enrollment returns a HttpResponse
        with no content
        """
        # add this post param to trigger a call to change_enrollment
        extra_post_params = {"enrollment_action": "enroll"}
        with patch('student.views.change_enrollment') as mock_change_enrollment:
            mock_change_enrollment.return_value = HttpResponse()
            response, _ = self._login_response(
                self.user_email, self.password, extra_post_params=extra_post_params,
            )
        response_content = json.loads(response.content.decode('utf-8'))
        self.assertIsNone(response_content["redirect_url"])
        self._assert_response(response, success=True)

    @override_settings(PASSWORD_POLICY_COMPLIANCE_ROLLOUT_CONFIG={'ENFORCE_COMPLIANCE_ON_LOGIN': True})
    def test_check_password_policy_compliance(self):
        """
        Tests _enforce_password_policy_compliance succeeds when no exception is thrown
        """
        enforce_compliance_path = 'openedx.core.djangoapps.password_policy.compliance.enforce_compliance_on_login'
        with patch(enforce_compliance_path) as mock_check_password_policy_compliance:
            mock_check_password_policy_compliance.return_value = HttpResponse()
            response, _ = self._login_response(self.user_email, self.password)
            response_content = json.loads(response.content.decode('utf-8'))
        self.assertTrue(response_content.get('success'))

    @override_settings(PASSWORD_POLICY_COMPLIANCE_ROLLOUT_CONFIG={'ENFORCE_COMPLIANCE_ON_LOGIN': True})
    def test_check_password_policy_compliance_exception(self):
        """
        Tests _enforce_password_policy_compliance fails with an exception thrown
        """
        enforce_compliance_on_login = '******'
        with patch(enforce_compliance_on_login) as mock_enforce_compliance_on_login:
            mock_enforce_compliance_on_login.side_effect = NonCompliantPasswordException()
            response, _ = self._login_response(
                self.user_email,
                self.password
            )
            response_content = json.loads(response.content.decode('utf-8'))
        self.assertFalse(response_content.get('success'))
        self.assertEqual(len(mail.outbox), 1)
        self.assertIn('Password reset', mail.outbox[0].subject)

    @override_settings(PASSWORD_POLICY_COMPLIANCE_ROLLOUT_CONFIG={'ENFORCE_COMPLIANCE_ON_LOGIN': True})
    def test_check_password_policy_compliance_warning(self):
        """
        Tests _enforce_password_policy_compliance succeeds with a warning thrown
        """
        enforce_compliance_on_login = '******'
        with patch(enforce_compliance_on_login) as mock_enforce_compliance_on_login:
            mock_enforce_compliance_on_login.side_effect = NonCompliantPasswordWarning('Test warning')
            response, _ = self._login_response(self.user_email, self.password)
            response_content = json.loads(response.content.decode('utf-8'))
            self.assertIn('Test warning', self.client.session['_messages'])
        self.assertTrue(response_content.get('success'))

    @ddt.data(
        ('test_password', 'test_password', True),
        (unicodedata.normalize('NFKD', u'Ṗŕệṿïệẅ Ṯệẍt'),
         unicodedata.normalize('NFKC', u'Ṗŕệṿïệẅ Ṯệẍt'), False),
        (unicodedata.normalize('NFKC', u'Ṗŕệṿïệẅ Ṯệẍt'),
         unicodedata.normalize('NFKD', u'Ṗŕệṿïệẅ Ṯệẍt'), True),
        (unicodedata.normalize('NFKD', u'Ṗŕệṿïệẅ Ṯệẍt'),
         unicodedata.normalize('NFKD', u'Ṗŕệṿïệẅ Ṯệẍt'), False),
    )
    @ddt.unpack
    def test_password_unicode_normalization_login(self, password, password_entered, login_success):
        """
        Tests unicode normalization on user's passwords on login.
        """
        self.user.set_password(password)
        self.user.save()
        response, _ = self._login_response(self.user.email, password_entered)
        self._assert_response(response, success=login_success)

    def _login_response(self, email, password, patched_audit_log=None, extra_post_params=None):
        """
        Post the login info
        """
        if patched_audit_log is None:
            patched_audit_log = 'openedx.core.djangoapps.user_authn.views.login.AUDIT_LOG'
        post_params = {'email': email, 'password': password}
        if extra_post_params is not None:
            post_params.update(extra_post_params)
        with patch(patched_audit_log) as mock_audit_log:
            result = self.client.post(self.url, post_params)
        return result, mock_audit_log

    def _assert_response(self, response, success=None, value=None):
        """
        Assert that the response had status 200 and returned a valid
        JSON-parseable dict.

        If success is provided, assert that the response had that
        value for 'success' in the JSON dict.

        If value is provided, assert that the response contained that
        value for 'value' in the JSON dict.
        """
        self.assertEqual(response.status_code, 200)

        try:
            response_dict = json.loads(response.content.decode('utf-8'))
        except ValueError:
            self.fail(u"Could not parse response content as JSON: %s"
                      % str(response.content))

        if success is not None:
            self.assertEqual(response_dict['success'], success)

        if value is not None:
            msg = (u"'%s' did not contain '%s'" %
                   (six.text_type(response_dict['value']), six.text_type(value)))
            self.assertIn(value, response_dict['value'], msg)

    def _assert_audit_log(self, mock_audit_log, level, log_strings):
        """
        Check that the audit log has received the expected call as its last call.
        """
        method_calls = mock_audit_log.method_calls
        name, args, _kwargs = method_calls[-1]
        self.assertEquals(name, level)
        self.assertEquals(len(args), 1)
        format_string = args[0]
        for log_string in log_strings:
            self.assertIn(log_string, format_string)

    def _assert_not_in_audit_log(self, mock_audit_log, level, log_strings):
        """
        Check that the audit log has received the expected call as its last call.
        """
        method_calls = mock_audit_log.method_calls
        name, args, _kwargs = method_calls[-1]
        self.assertEquals(name, level)
        self.assertEquals(len(args), 1)
        format_string = args[0]
        for log_string in log_strings:
            self.assertNotIn(log_string, format_string)
Exemple #38
0
class TestWorkshopViews(WousoTest):
    def setUp(self):
        super(TestWorkshopViews, self).setUp()
        self.admin = self._get_superuser()
        self.c = Client()
        self.c.login(username='******', password='******')

    def test_add_group_view_get(self):
        response = self.c.get(reverse('ws_add_group'))
        self.assertContains(response, 'Name')
        self.assertContains(response, 'Day')
        self.assertContains(response, 'Hour')
        self.assertContains(response, 'Room')

    def test_add_group_view_post(self):
        data = {u'room': u'ef108',
                u'name': u'semigroup_test',
                u'hour': u'10',
                u'day': u'1'}
        response = self.c.post(reverse('ws_add_group'), data)

        # Check if it redirects
        self.assertEqual(response.status_code, 302)

        # Check if it creates a semigroup
        self.assertTrue(Semigroup.objects.all())

        # Check if duplicates are created
        response = self.c.post(reverse('ws_add_group'), data)
        self.assertEqual(len(Semigroup.objects.all()), 1)

    def test_edit_group_view_get(self):
        sg = Semigroup.objects.create(day=u'1', hour=u'10', name=u'semigroup_test')
        response = self.c.get(reverse('ws_edit_group', args=[sg.pk]))
        self.assertContains(response, 'Name')
        self.assertContains(response, 'value="semigroup_test"')

    def test_edit_group_view_post(self):
        sg = Semigroup.objects.create(day=u'1', hour=u'10', name=u'semigroup_test')
        self.assertEqual(sg.room, u'eg306')
        data = {u'room': u'ef108',
                u'name': u'semigroup_test',
                u'hour': u'10',
                u'day': u'1'}
        response = self.c.post(reverse('ws_edit_group', args=[sg.pk]), data)
        sg = Semigroup.objects.get(name=u'semigroup_test')
        self.assertEqual(sg.room, u'ef108')

        # Check if user is redirected
        self.assertEqual(response.status_code, 302)

    def test_schedule_change_view_get(self):
        sch = Schedule.objects.create(name='schedule_test')
        # Get the response for editing a schedule URL:'schedule/edit/(?P<schedule>\d+)/'
        response = self.c.get(reverse('ws_schedule_change', args=[sch.pk]))
        self.assertContains(response, 'Name')
        self.assertContains(response, 'value="schedule_test"')

        # Get the response for adding a schedule URL:'schedule/add/'
        response = self.c.get(reverse('ws_schedule_change'))
        self.assertContains(response, 'Name')

    def test_schedule_change_view_post(self):
        today = datetime.today()
        sch = Schedule.objects.create(name='schedule_test')
        data = {u'name': u'schedule_new_name',
                u'start_date': today.date(),
                u'end_date': today.date(),
                u'count': 5}
        response = self.c.post(reverse('ws_schedule_change', args=[sch.pk]), data)
        sch = Schedule.objects.get(pk=sch.pk)
        self.assertEqual(sch.name, 'schedule_new_name')

    def test_workshop_add_view_get(self):
        response = self.c.get(reverse('ws_add_workshop'))
        self.assertContains(response, 'Semigroup')
        self.assertContains(response, 'Date')
        self.assertContains(response, 'Question count')

    def test_workshop_add_view_post(self):
        sg = Semigroup.objects.create(day=u'1', hour=u'10', name=u'semigroup_test')
        workshops = Workshop.objects.all()
        self.assertFalse(workshops)

        today = datetime.today()
        data = {u'semigroup': sg.id,
                u'date': today.date(),
                u'question_count': u'5'}
        response = self.c.post(reverse('ws_add_workshop'), data)
        workshops = Workshop.objects.all()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(len(workshops), 1)

        # Check view without selecting a semigroup
        data = {u'semigroup': u'',
                u'date': today.date(),
                u'question_count': u'5'}
        response = self.c.post(reverse('ws_add_workshop'), data)
        self.assertContains(response, 'This field is required')

    def test_gradebook_view(self):
        sg = Semigroup.objects.create(day=u'1', hour=u'10', name=u'semigroup_test')
        pl1 = self._get_player(1)
        pl2 = self._get_player(2)
        sg.players.add(pl1, pl2)

        response = self.c.get(reverse('ws_gradebook', args=[sg.id]))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'testuser1')
        self.assertContains(response, 'testuser2')
Exemple #39
0
class TestSaveSwarms(object):
    def setup(self):

        self.app = models.App(
            name=randchars(),
            repo_url=randchars(),
            repo_type=randchars(),
        )
        self.app.save()

        self.app2 = models.App(
            name=randchars(),
            repo_url=randchars(),
            repo_type=randchars(),
        )
        self.app2.save()

        self.build = models.Build(
            app=self.app,
            tag=randchars(),
            file=randchars(),
            status='success',
            hash=randchars(),
        )
        self.build.save()

        self.build2 = models.Build(
            app=self.app2,
            tag=randchars(),
            file=randchars(),
            status='success',
            hash=randchars(),
        )
        self.build2.save()

        self.release = models.Release(
            build=self.build,
            config_yaml='',
            env_yaml='',
            hash=randchars(),
        )
        self.release.save()

        self.release2 = models.Release(
            build=self.build2,
            config_yaml='',
            env_yaml='',
            hash=randchars(),
        )
        self.release2.save()

        self.squad = models.Squad(name=randchars())
        self.squad.save()

        # create a swarm object
        self.swarm = models.Swarm(
            app=self.app,
            release=self.release,
            config_name=randchars(),
            proc_name='web',
            squad=self.squad,
        )
        self.swarm.save()

        self.swarm2 = models.Swarm(
            app=self.app2,
            release=self.release2,
            config_name=randchars(),
            proc_name='web',
            squad=self.squad,
        )
        self.swarm2.save()

        dashboard_name = randchars()
        self.dashboard = models.Dashboard(
            name=dashboard_name,
            slug=slugify(dashboard_name),
        )
        self.dashboard.save()
        self.dashboard.apps.add(self.app2)

        # Get a logged in client ready
        self.user = get_user()
        models.UserProfile.objects.create(user=self.user)
        self.user.userprofile.default_dashboard = self.dashboard
        self.user.userprofile.save()
        self.client = Client()
        self.client.post(reverse('login'), {
            'username': self.user.username,
            'password': '******'
        })

    def test_simple_update(self, redis):

        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm.id})
        payload = {
            'app_id':
            self.swarm.app.id,
            'os_image_id':
            getattr(self.swarm.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm.squad.id,
            'tag':
            randchars(),
            'config_name':
            self.swarm.config_name,
            'config_yaml':
            yamlize(self.swarm.config_yaml),
            'env_yaml':
            yamlize(self.swarm.env_yaml),
            'volumes':
            yamlize(self.swarm.volumes),
            'run_as':
            self.swarm.run_as or 'nobody',
            'mem_limit':
            self.swarm.mem_limit,
            'memsw_limit':
            self.swarm.memsw_limit,
            'proc_name':
            self.swarm.proc_name,
            'size':
            self.swarm.size,
            'pool':
            self.swarm.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm.config_ingredients.all()]
        }
        previous_release_id = self.swarm.release_id
        self.client.post(url, data=payload)
        saved = models.Swarm.objects.get(id=self.swarm.id)
        new_release_id = saved.release_id
        assert previous_release_id != new_release_id

    def test_invalid_tags(self):
        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm.id})
        invalid_tags = [
            'gittag/v1', 'my:tag', '^tag', '~other:tag', 'tag?'
            'other*tag'
            '\\tag', 'a tag'
        ]
        payload = {
            'app_id':
            self.swarm.app.id,
            'os_image_id':
            getattr(self.swarm.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm.squad.id,
            'config_name':
            self.swarm.config_name,
            'config_yaml':
            yamlize(self.swarm.config_yaml),
            'env_yaml':
            yamlize(self.swarm.env_yaml),
            'volumes':
            yamlize(self.swarm.volumes),
            'run_as':
            self.swarm.run_as or 'nobody',
            'mem_limit':
            self.swarm.mem_limit,
            'memsw_limit':
            self.swarm.memsw_limit,
            'proc_name':
            self.swarm.proc_name,
            'size':
            self.swarm.size,
            'pool':
            self.swarm.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm.config_ingredients.all()]
        }
        for tag in invalid_tags:
            payload['tag'] = tag
            resp = self.client.post(url, data=payload)
            assert 'Invalid tag name' in resp.content.decode('utf-8')

    def test_normal_app_update_redirection(self, redis):
        """
        Test that after swarming an app not in the user's default dashboard,
        he/she gets redirected to the 'Home' section.

        See self.setUp() for more info.
        """
        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm.id})
        payload = {
            'app_id':
            self.swarm.app.id,
            'os_image_id':
            getattr(self.swarm.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm.squad.id,
            'tag':
            randchars(),
            'config_name':
            self.swarm.config_name,
            'config_yaml':
            yamlize(self.swarm.config_yaml),
            'env_yaml':
            yamlize(self.swarm.env_yaml),
            'volumes':
            yamlize(self.swarm.volumes),
            'run_as':
            self.swarm.run_as or 'nobody',
            'mem_limit':
            self.swarm.mem_limit,
            'memsw_limit':
            self.swarm.memsw_limit,
            'proc_name':
            self.swarm.proc_name,
            'size':
            self.swarm.size,
            'pool':
            self.swarm.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm.config_ingredients.all()]
        }
        resp = self.client.post(url, data=payload)
        assert resp._headers['location'][1] == 'http://testserver/'

    def test_dashboard_app_update_redirection(self, redis):
        """
        Test that after swarming an app that belongs to the user's default
        dashboard, he/she gets redirected to /dashboard/.

        See self.setUp() for more info.
        """
        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm2.id})
        payload = {
            'app_id':
            self.swarm2.app.id,
            'os_image_id':
            getattr(self.swarm2.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm2.squad.id,
            'tag':
            randchars(),
            'config_name':
            self.swarm2.config_name,
            'config_yaml':
            yamlize(self.swarm2.config_yaml),
            'env_yaml':
            yamlize(self.swarm2.env_yaml),
            'volumes':
            yamlize(self.swarm2.volumes),
            'run_as':
            self.swarm2.run_as or 'nobody',
            'mem_limit':
            self.swarm2.mem_limit,
            'memsw_limit':
            self.swarm2.memsw_limit,
            'proc_name':
            self.swarm2.proc_name,
            'size':
            self.swarm2.size,
            'pool':
            self.swarm2.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm2.config_ingredients.all()]
        }
        resp = self.client.post(url, data=payload)
        assert resp._headers['location'][1] == 'http://testserver/dashboard/'

    @pytest.mark.skipif(
        "sys.version_info > (3,)",
        reason="Int keys are allowed on Python 3",
    )
    def test_config_yaml_marshaling(self):

        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm.id})
        payload = {
            'app_id':
            self.swarm.app.id,
            'os_image_id':
            getattr(self.swarm.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm.squad.id,
            'tag':
            randchars(),
            'config_name':
            self.swarm.config_name,
            'config_yaml':
            '1: integer key not allowed',
            'env_yaml':
            yamlize(self.swarm.env_yaml),
            'volumes':
            yamlize(self.swarm.volumes),
            'run_as':
            self.swarm.run_as or 'nobody',
            'mem_limit':
            self.swarm.mem_limit,
            'memsw_limit':
            self.swarm.memsw_limit,
            'proc_name':
            self.swarm.proc_name,
            'size':
            self.swarm.size,
            'pool':
            self.swarm.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm.config_ingredients.all()]
        }
        resp = self.client.post(url, data=payload)
        assert "Cannot be marshalled to XMLRPC" in resp.content

    @pytest.mark.skipif(
        "sys.version_info > (3,)",
        reason="Big int is allowed on Python 3",
    )
    def test_env_yaml_marshaling(self):

        url = reverse('edit_swarm', kwargs={'swarm_id': self.swarm.id})
        payload = {
            'app_id':
            self.swarm.app.id,
            'os_image_id':
            getattr(self.swarm.release.build.os_image, 'id', ''),
            'squad_id':
            self.swarm.squad.id,
            'tag':
            randchars(),
            'config_name':
            self.swarm.config_name,
            'config_yaml':
            yamlize(self.swarm.config_yaml),
            'env_yaml':
            'TOO_BIG_NUMBER: 1234123412341234',
            'volumes':
            yamlize(self.swarm.volumes),
            'run_as':
            self.swarm.run_as or 'nobody',
            'mem_limit':
            self.swarm.mem_limit,
            'memsw_limit':
            self.swarm.memsw_limit,
            'proc_name':
            self.swarm.proc_name,
            'size':
            self.swarm.size,
            'pool':
            self.swarm.pool or '',
            'balancer':
            '',
            'config_ingredients':
            [ing.pk for ing in self.swarm.config_ingredients.all()]
        }
        resp = self.client.post(url, data=payload)
        assert "Cannot be marshalled to XMLRPC" in resp.content
class MemberJoinLoginTest(TestMixin, WebTest):
    def setUp(self):
        super(MemberJoinLoginTest, self).setUp()
        self.client = Client()

    def test_join_member_current_data(self):
        last_member_num = Member.objects.count()
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data,
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(last_member_num + 1, Member.objects.count())
        self.assertEqual(Member.objects.last().primary_user.username,
                         self.join_data['username'])
        self.assertRedirects(response, reverse('members:login'))

    def test_join_member_wrong_username(self):
        last_member_num = Member.objects.count()
        self.join_data['username'] = '******'
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(last_member_num, Member.objects.count())
        self.assertContains(response,
                            'Username should be at least 6 characters long.')
        self.join_data['username'] = '******'
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(last_member_num, Member.objects.count())
        self.assertContains(
            response,
            'Valid characters are numbers, lowercase letters and dashes.')

    def test_blank_fields(self):
        response = self.client.get(reverse('members:join'))
        self.assertEqual(response.status_code, 200)
        mem_count = Member.objects.count()
        self.join_data.update({'username': ""})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertFormError(response, 'form', 'username',
                             ['This field is required.'])
        self.assertEqual(mem_count, Member.objects.count())
        self.join_data.update({'username': "******"})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(mem_count + 1, Member.objects.count())
        self.assertEqual(Member.objects.last().primary_user.username,
                         self.join_data['username'])

        User.objects.last().delete()
        self.assertEqual(mem_count, Member.objects.count())
        self.join_data.update({'password': ""})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(mem_count, Member.objects.count())
        self.assertFormError(response, 'form', 'password',
                             ['This field is required.'])
        self.join_data.update({'password': "******"})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(mem_count + 1, Member.objects.count())
        self.assertEqual(Member.objects.last().primary_user.username,
                         self.join_data['username'])
        User.objects.last().delete()
        self.assertEqual(mem_count, Member.objects.count())
        self.join_data.update({
            'password': "",
            'first_name': "",
            'last_name': "",
            'national_id': ""
        })
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(mem_count, Member.objects.count())
        self.assertFormError(response, 'form', 'password',
                             ['This field is required.'])
        self.assertFormError(response, 'form', 'national_id',
                             ['This field is required.'])

    def test_password_matching(self):
        response = self.client.get(reverse('members:join'))
        self.assertEqual(response.status_code, 200)
        mem_count = Member.objects.count()
        password = self.join_data['password']
        self.join_data.update({'password': '******'})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertContains(response, 'Passwords not match.')
        self.assertEqual(mem_count, Member.objects.count())
        self.join_data.update({'password': ''})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertNotContains(response, 'Passwords not match.')
        self.assertFormError(response, 'form', 'password',
                             ['This field is required.'])
        self.assertEqual(mem_count, Member.objects.count())
        self.join_data.update({'password': password, 're_password': ""})
        response = self.client.post(reverse('members:join'),
                                    data=self.join_data)
        self.assertNotContains(response, 'Passwords not match.')
        self.assertFormError(response, 'form', 're_password',
                             ['This field is required.'])
        self.assertEqual(mem_count, Member.objects.count())

    def test_duplicate_username_or_email(self):
        self.client.post(reverse('members:join'),
                         data=self.join_data,
                         follow=True)
        email = self.join_data['email']
        self.join_data.update({'email': '*****@*****.**'})
        username_response = self.client.post(reverse('members:join'),
                                             self.join_data,
                                             follow=True)
        self.assertContains(username_response, 'Your username already exists')
        self.join_data.update({'username': '******', 'email': email})
        email_response = self.client.post(reverse('members:join'),
                                          self.join_data,
                                          follow=True)
        self.assertContains(email_response,
                            'Your email address already exists')

    def test_login_user(self):
        self.client.post(reverse('members:join'), data=self.join_data)
        response = self.client.post(reverse('members:login'),
                                    data=self.login_data,
                                    follow=True)
        self.assertTemplateUsed(response, 'home_member.html')
        response = self.client.get(reverse('members:login'))
        self.assertEqual(response.status_code, 302)
        self.client.logout()
        self.assertNotIn(container=self.client.session, member='_auth_user_id')
        response = self.client.post(reverse('members:login'),
                                    data=self.login_data)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('home'))
        self.assertIn(container=self.client.session, member='_auth_user_id')
        self.client.logout()
        self.assertNotIn(container=self.client.session, member='_auth_user_id')
        password = self.join_data['password']
        self.login_data.update({'password': '******'})
        response = self.client.post(reverse('members:login'),
                                    data=self.login_data)
        self.assertContains(response, 'Username or Password is incorrect')
        response = self.client.get(path=reverse('members:login'))
        self.assertEqual(response.status_code, 200)
        self.login_data.update({'password': password})
        response = self.client.post(reverse('members:login'),
                                    data=self.login_data)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('home'))
        self.assertIn(container=self.client.session, member='_auth_user_id')
        response = self.client.get(path=reverse('members:login'))
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('home'))
Exemple #41
0
class FunctionalTest(unittest.TestCase):
    def setUp(self):
        self.c = Client()

    def test_index(self):
        response = self.c.get("/debian/")
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertTrue('debian/search.html' in template_names)
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/search/assisted-search.html' in template_names)
        self.assertTrue('debian/search/sparql.html' in template_names)
        self.assertTrue('debian/search/help.html' in template_names)
        self.assertEqual("text/html; charset=utf-8", response['Content-Type'])

    def test_index_post(self):
        response = self.c.post("/debian/")
        self.failUnlessEqual(response.status_code, 405)

    def test_results_get(self):
        response = self.c.get("/debian/results/")
        self.failUnlessEqual(response.status_code, 405)

    def test_sparql_get(self):
        response = self.c.get("/debian/sparql/")
        self.failUnlessEqual(response.status_code, 405)

    def test_binaries_post(self):
        response = self.c.post("/debian/binaries/sourcename/version/")
        self.failUnlessEqual(response.status_code, 405)

    def test_news_post(self):
        response = self.c.post("/debian/news/sourcename/")
        self.failUnlessEqual(response.status_code, 405)

    def test_allnews_get(self):
        response = self.c.get("/debian/results/news/")
        self.failUnlessEqual(response.status_code, 405)

    def test_binaries_badsourcename(self):
        response = self.c.get("/debian/binaries/%7B/1.0/")
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/error.html' in template_names)

    def test_news_badsourcename(self):
        response = self.c.get("/debian/news/%7B/")
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/error.html' in template_names)

    def test_assisted_search_html_source(self):
        body = {
            'sort': 'PACKAGE',
            'priority': 'ANY',
            'maintainer': 'ALL',
            'searchtype': 'SOURCE',
            'area': 'ANY',
            'section': '',
            'filter': '',
            'comaintainer': 'ALL',
            'distribution': 'ANY'
        }
        response = self.c.post("/debian/results/", body)
        template_names = [x.name for x in response.template]
        self.failUnlessEqual(response.status_code, 200)
        self.assertEqual("text/html; charset=utf-8", response['Content-Type'])
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/source_results.html' in template_names)

    def test_assisted_search_html_binary(self):
        body = {
            'sort': 'PACKAGE',
            'priority': 'ANY',
            'maintainer': 'ALL',
            'searchtype': 'BINARY',
            'area': 'ANY',
            'section': '',
            'filter': '',
            'comaintainer': 'ALL',
            'distribution': 'ANY'
        }
        response = self.c.post("/debian/results/", body)
        template_names = [x.name for x in response.template]
        self.failUnlessEqual(response.status_code, 200)
        self.assertEqual("text/html; charset=utf-8", response['Content-Type'])
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/binary_results.html' in template_names)

    def test_assisted_search_json(self):
        body = {
            'sort': 'PACKAGE',
            'priority': 'ANY',
            'maintainer': 'ALL',
            'searchtype': 'SOURCE',
            'area': 'ANY',
            'section': '',
            'filter': '',
            'comaintainer': 'ALL',
            'distribution': 'ANY',
            'tojson': 'on'
        }
        response = self.c.post("/debian/results/", body)
        self.failUnlessEqual(response.status_code, 200)
        self.assertEqual("application/json", response['Content-Type'])

    def test_malformed_sparql_query(self):
        query = "SELECT * WHERE { ?s ?p }"
        body = {'ns': '', 'query': query}
        response = self.c.post("/debian/sparql/", body)
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/error.html' in template_names)
        e = SPARQLQueryProcessorQueryBadFormedError()
        self.assertEqual(e, response.context['reason'])

    def test_malformed_sparql_query_mistyped_type(self):
        query = "SLECT * WHERE { ?s ?p ?o . }"
        body = {'ns': '', 'query': query}
        response = self.c.post("/debian/sparql/", body)
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/error.html' in template_names)
        e = SPARQLQueryProcessorQueryBadFormedError()
        self.assertEqual(e, response.context['reason'])

    def test_malformed_sparql_query_unsupported_type(self):
        query = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o . }"
        body = {'ns': '', 'query': query}
        response = self.c.post("/debian/sparql/", body)
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/error.html' in template_names)
        e = SPARQLQueryProcessorUnacceptableQueryFormatError()
        self.assertEqual(e, response.context['reason'])

    def test_malformed_sparql_query_ok(self):
        query = "SELECT * WHERE { ?s ?p ?o . }"
        body = {'ns': '', 'query': query}
        response = self.c.post("/debian/sparql/", body)
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/results.html' in template_names)

    # Will fail in non-virtuoso stores
    def test_malformed_sparql_query_ok2(self):
        ns = "PREFIX deb:<http://idi.fundacionctic.org/steamy/debian.owl#>"
        query = """
SELECT ?s COUNT(?d) as ?c
WHERE {

?s deb:distribution ?d

} 
ORDER BY DESC(?c)"""
        body = {'ns': ns, 'query': query}
        response = self.c.post("/debian/sparql/", body)
        self.failUnlessEqual(response.status_code, 200)
        template_names = [x.name for x in response.template]
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/results.html' in template_names)

    def test_result_based_news(self):
        body = {
            'sort': 'PACKAGE',
            'priority': 'ANY',
            'maintainer': 'ALL',
            'searchtype': 'BINARY',
            'area': 'ANY',
            'section': '',
            'filter': '',
            'comaintainer': 'ALL',
            'distribution': 'ANY'
        }
        response = self.c.post("/debian/results/news/", body)
        template_names = [x.name for x in response.template]
        self.failUnlessEqual(response.status_code, 200)
        self.assertEqual("text/html; charset=utf-8", response['Content-Type'])
        self.assertEqual(2, len(template_names))
        self.assertTrue('debian/base.html' in template_names)
        self.assertTrue('debian/news.html' in template_names)
Exemple #42
0
class TestDecide(BaseTest):
    """
    Tests the `/decide` endpoint.
    We use Django's base test class instead of DRF's because we need granular control over the Content-Type sent over.
    """
    def setUp(self):
        super().setUp()
        self.client = Client()
        self.client.force_login(self.user)

    def _dict_to_b64(self, data: dict) -> str:
        return base64.b64encode(
            json.dumps(data).encode("utf-8")).decode("utf-8")

    def _post_decide(self,
                     data=None,
                     origin="http://127.0.0.1:8000",
                     api_version=1,
                     distinct_id="example_id",
                     groups={}):
        return self.client.post(
            f"/decide/?v={api_version}",
            {
                "data":
                self._dict_to_b64(
                    data or {
                        "token": self.team.api_token,
                        "distinct_id": distinct_id,
                        "groups": groups
                    })
            },
            HTTP_ORIGIN=origin,
        )

    def test_defaults_to_v2_if_conflicting_parameters(self):
        """
        regression test for https://sentry.io/organizations/posthog2/issues/2738865125/?project=1899813
        posthog-js version 1.19.0 (but not versions before or after)
        mistakenly sent two `v` parameters to the decide endpoint
        one was correct "2"
        the other incorrect "1.19.0"

        as a result, if there is a value error reading the `v` param, decide now defaults to 2
        """

        response = self.client.post(
            f"/decide/?v=2&v=1.19.0",
            {
                "data":
                self._dict_to_b64({
                    "token": self.team.api_token,
                    "distinct_id": "example_id",
                    "groups": {}
                })
            },
            HTTP_ORIGIN="http://127.0.0.1:8000",
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_user_on_own_site_enabled(self):
        user = self.organization.members.first()
        user.toolbar_mode = "toolbar"
        user.save()

        self.team.app_urls = ["https://example.com/maybesubdomain"]
        self.team.save()
        response = self.client.get("/decide/",
                                   HTTP_ORIGIN="https://example.com").json()
        self.assertEqual(response["isAuthenticated"], True)
        self.assertEqual(response["supportedCompression"],
                         ["gzip", "gzip-js", "lz64"])
        self.assertEqual(response["editorParams"]["toolbarVersion"], "toolbar")

    def test_user_on_own_site_disabled(self):
        user = self.organization.members.first()
        user.toolbar_mode = "disabled"
        user.save()

        self.team.app_urls = ["https://example.com/maybesubdomain"]
        self.team.save()

        # Make sure the endpoint works with and without the trailing slash
        response = self.client.get("/decide",
                                   HTTP_ORIGIN="https://example.com").json()
        self.assertEqual(response["isAuthenticated"], True)
        self.assertIsNone(response["editorParams"].get("toolbarVersion"))

    def test_user_on_evil_site(self):
        user = self.organization.members.first()
        user.toolbar_mode = "toolbar"
        user.save()

        self.team.app_urls = ["https://example.com"]
        self.team.save()
        response = self.client.get("/decide/",
                                   HTTP_ORIGIN="https://evilsite.com").json()
        self.assertEqual(response["isAuthenticated"], False)
        self.assertIsNone(response["editorParams"].get("toolbarVersion", None))

    def test_user_on_local_host(self):
        user = self.organization.members.first()
        user.toolbar_mode = "toolbar"
        user.save()

        self.team.app_urls = ["https://example.com"]
        self.team.save()
        response = self.client.get("/decide",
                                   HTTP_ORIGIN="http://127.0.0.1:8000").json()
        self.assertEqual(response["isAuthenticated"], True)
        self.assertEqual(response["sessionRecording"], False)
        self.assertEqual(response["editorParams"]["toolbarVersion"], "toolbar")
        self.assertEqual(response["supportedCompression"],
                         ["gzip", "gzip-js", "lz64"])

    def test_user_session_recording_opt_in(self):
        # :TRICKY: Test for regression around caching
        response = self._post_decide().json()
        self.assertEqual(response["sessionRecording"], False)

        self.team.session_recording_opt_in = True
        self.team.save()

        response = self._post_decide().json()
        self.assertEqual(response["sessionRecording"], {"endpoint": "/s/"})
        self.assertEqual(response["supportedCompression"],
                         ["gzip", "gzip-js", "lz64"])

    def test_user_session_recording_opt_in_wildcard_domain(self):
        # :TRICKY: Test for regression around caching
        response = self._post_decide().json()
        self.assertEqual(response["sessionRecording"], False)

        self.team.session_recording_opt_in = True
        self.team.app_urls = ["https://*.example.com"]
        self.team.save()

        response = self._post_decide(
            origin="https://random.example.com").json()
        self.assertEqual(response["sessionRecording"], {"endpoint": "/s/"})
        self.assertEqual(response["supportedCompression"],
                         ["gzip", "gzip-js", "lz64"])

        # Make sure the domain matches exactly
        response = self._post_decide(
            origin="https://random.example.com.evilsite.com").json()
        self.assertEqual(response["sessionRecording"], False)

    def test_user_session_recording_evil_site(self):
        self.team.app_urls = ["https://example.com"]
        self.team.session_recording_opt_in = True
        self.team.save()

        response = self._post_decide(origin="evil.site.com").json()
        self.assertEqual(response["sessionRecording"], False)

        response = self._post_decide(origin="https://example.com").json()
        self.assertEqual(response["sessionRecording"], {"endpoint": "/s/"})

    def test_feature_flags(self):
        self.team.app_urls = ["https://example.com"]
        self.team.save()
        self.client.logout()
        Person.objects.create(team=self.team,
                              distinct_ids=["example_id"],
                              properties={"email": "*****@*****.**"})
        FeatureFlag.objects.create(
            team=self.team,
            rollout_percentage=50,
            name="Beta feature",
            key="beta-feature",
            created_by=self.user,
        )
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }]
            },
            name="This is a feature flag with default params, no filters.",
            key="default-flag",
            created_by=self.user,
        )  # Should be enabled for everyone

        # Test number of queries with multiple property filter feature flags
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "properties": [{
                    "key": "email",
                    "value": "*****@*****.**",
                    "type": "person"
                }]
            },
            rollout_percentage=50,
            name="Filter by property",
            key="filer-by-property",
            created_by=self.user,
        )
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [{
                        "key": "email",
                        "value": "*****@*****.**",
                        "type": "person"
                    }]
                }]
            },
            name="Filter by property 2",
            key="filer-by-property-2",
            created_by=self.user,
        )

        with self.assertNumQueries(5):
            response = self._post_decide()
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("default-flag", response.json()["featureFlags"])
        self.assertIn("beta-feature", response.json()["featureFlags"])
        self.assertIn("filer-by-property-2", response.json()["featureFlags"])

        with self.assertNumQueries(5):
            response = self._post_decide({
                "token": self.team.api_token,
                "distinct_id": "another_id"
            })
            self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()["featureFlags"], ["default-flag"])

    def test_feature_flags_v2(self):
        self.team.app_urls = ["https://example.com"]
        self.team.save()
        self.client.logout()
        Person.objects.create(team=self.team,
                              distinct_ids=["example_id"],
                              properties={"email": "*****@*****.**"})
        FeatureFlag.objects.create(
            team=self.team,
            rollout_percentage=50,
            name="Beta feature",
            key="beta-feature",
            created_by=self.user,
        )
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }]
            },
            name="This is a feature flag with default params, no filters.",
            key="default-flag",
            created_by=self.user,
        )  # Should be enabled for everyone
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }],
                "multivariate": {
                    "variants": [
                        {
                            "key": "first-variant",
                            "name": "First Variant",
                            "rollout_percentage": 50
                        },
                        {
                            "key": "second-variant",
                            "name": "Second Variant",
                            "rollout_percentage": 25
                        },
                        {
                            "key": "third-variant",
                            "name": "Third Variant",
                            "rollout_percentage": 25
                        },
                    ],
                },
            },
            name="This is a feature flag with multiple variants.",
            key="multivariate-flag",
            created_by=self.user,
        )

        with self.assertNumQueries(3):
            response = self._post_decide(
                api_version=1)  # v1 functionality should not break
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertIn("beta-feature", response.json()["featureFlags"])
            self.assertIn("default-flag", response.json()["featureFlags"])

        with self.assertNumQueries(3):
            response = self._post_decide(api_version=2)
            self.assertTrue(response.json()["featureFlags"]["beta-feature"])
            self.assertTrue(response.json()["featureFlags"]["default-flag"])
            self.assertEqual(
                "first-variant",
                response.json()["featureFlags"]
                ["multivariate-flag"])  # assigned by distinct_id hash

        with self.assertNumQueries(3):
            response = self._post_decide(api_version=2, distinct_id="other_id")
            self.assertTrue(response.json()["featureFlags"]["beta-feature"])
            self.assertTrue(response.json()["featureFlags"]["default-flag"])
            self.assertEqual(
                "third-variant",
                response.json()["featureFlags"]["multivariate-flag"]
            )  # different hash, different variant assigned

    def test_feature_flags_v2_complex(self):
        self.team.app_urls = ["https://example.com"]
        self.team.save()
        self.client.logout()
        Person.objects.create(team=self.team,
                              distinct_ids=["example_id"],
                              properties={
                                  "email": "*****@*****.**",
                                  "realm": "cloud"
                              })
        Person.objects.create(team=self.team,
                              distinct_ids=["hosted_id"],
                              properties={
                                  "email": "*****@*****.**",
                                  "realm": "hosted"
                              })
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }]
            },
            name="This is a feature flag with default params, no filters.",
            key="default-flag",
            created_by=self.user,
        )  # Should be enabled for everyone
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [{
                        "key": "realm",
                        "type": "person",
                        "value": "cloud"
                    }],
                    "rollout_percentage":
                    80
                }],
                "multivariate": {
                    "variants": [
                        {
                            "key": "first-variant",
                            "name": "First Variant",
                            "rollout_percentage": 25
                        },
                        {
                            "key": "second-variant",
                            "name": "Second Variant",
                            "rollout_percentage": 25
                        },
                        {
                            "key": "third-variant",
                            "name": "Third Variant",
                            "rollout_percentage": 25
                        },
                        {
                            "key": "fourth-variant",
                            "name": "Fourth Variant",
                            "rollout_percentage": 25
                        },
                    ],
                },
            },
            name=
            "This is a feature flag with top-level property filtering and percentage rollout.",
            key="multivariate-flag",
            created_by=self.user,
        )

        with self.assertNumQueries(4):
            response = self._post_decide(api_version=2,
                                         distinct_id="hosted_id")
            self.assertIsNone(
                (response.json()["featureFlags"]).get("multivariate-flag",
                                                      None)
            )  # User is does not have realm == "cloud". Value is None.
            self.assertTrue(
                (response.json()["featureFlags"]
                 ).get("default-flag"))  # User still receives the default flag

        with self.assertNumQueries(4):
            response = self._post_decide(api_version=2,
                                         distinct_id="example_id")
            self.assertIsNotNone(
                response.json()["featureFlags"]["multivariate-flag"]
            )  # User has an 80% chance of being assigned any non-empty value.
            self.assertEqual(
                "second-variant",
                response.json()["featureFlags"]["multivariate-flag"]
            )  # If the user falls in the rollout group, they have a 25% chance of being assigned any particular variant.
            # Their overall probability is therefore 80% * 25% = 20%.
            # To give another example, if n = 100 Cloud users and rollout_percentage = 80:
            # None:           20 (100 * (100% - 80%))
            # first-variant:  20 (100 * 80% * 25% = 20 users)
            # second-variant: 20 (100 * 80% * 25% = 20 users)
            # third-variant:  20 (100 * 80% * 25% = 20 users)
            # fourth-variant: 20 (100 * 80% * 25% = 20 users)

    def test_feature_flags_v2_override(self):
        self.user.distinct_id = "static-distinct-id"
        self.user.save()
        self.team.app_urls = ["https://example.com"]
        self.team.save()
        self.client.logout()
        Person.objects.create(
            team=self.team,
            distinct_ids=[self.user.distinct_id, "not-canonical-distinct-id"],
            properties={"email": self.user.email},
        )
        ff_1 = FeatureFlag.objects.create(
            team=self.team,
            name="Full rollout feature",
            rollout_percentage=100,
            key="bool-key-overridden-to-false",
            created_by=self.user,
        )  # Overriden to False

        ff_2 = FeatureFlag.objects.create(
            team=self.team,
            name="Zero rollout feature",
            rollout_percentage=0,
            key="bool-key-overridden-to-true",
            created_by=self.user,
        )  # Overriden to True

        ff_3 = FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }],
                "multivariate": {
                    "variants": [
                        {
                            "key": "first-variant",
                            "name": "First Variant",
                            "rollout_percentage": 100
                        },
                        {
                            "key": "second-variant",
                            "name": "Second Variant",
                            "rollout_percentage": 0
                        },
                        {
                            "key": "third-variant",
                            "name": "Third Variant",
                            "rollout_percentage": 0
                        },
                    ],
                },
            },
            name="This is a multi var feature flag that gets overriden.",
            key="multivariate-flag-overridden",
            created_by=self.user,
        )  # Multi-var overriden to diff variant

        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }],
                "multivariate": {
                    "variants": [
                        {
                            "key": "first-variant",
                            "name": "First Variant",
                            "rollout_percentage": 0
                        },
                        {
                            "key": "second-variant",
                            "name": "Second Variant",
                            "rollout_percentage": 100
                        },
                        {
                            "key": "third-variant",
                            "name": "Third Variant",
                            "rollout_percentage": 0
                        },
                    ],
                },
            },
            name="This is a multi var feature flag that doens't get overriden.",
            key="multivariate-flag-not-overridden",
            created_by=self.user,
        )  # Multi-var not overriden

        FeatureFlag.objects.create(
            team=self.team,
            name="This is a feature flag with default params, no filters.",
            key="flag-rollout-100",
            rollout_percentage=100,
            created_by=self.user,
        )  # True feature flag, not overriden

        FeatureFlag.objects.create(
            team=self.team,
            name="This is a feature flag with default params, no filters.",
            key="flag-rollout-0",
            rollout_percentage=0,
            created_by=self.user,
        )  # False feature flag, not overriden

        FeatureFlagOverride.objects.create(
            team=self.team,
            user=self.user,
            feature_flag=ff_1,
            override_value=False,
        )
        FeatureFlagOverride.objects.create(
            team=self.team,
            user=self.user,
            feature_flag=ff_2,
            override_value=True,
        )
        FeatureFlagOverride.objects.create(
            team=self.team,
            user=self.user,
            feature_flag=ff_3,
            override_value="third-variant",
        )

        with self.assertNumQueries(3):
            response = self._post_decide(api_version=1,
                                         distinct_id=str(
                                             self.user.distinct_id))
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(
                response.json()["featureFlags"],
                [
                    "multivariate-flag-overridden",
                    "multivariate-flag-not-overridden",
                    "flag-rollout-100",
                    "bool-key-overridden-to-true",
                ],
            )

        with self.assertNumQueries(3):
            response = self._post_decide(api_version=2,
                                         distinct_id=str(
                                             self.user.distinct_id))
            feature_flags_for_canonical_distinct_id = response.json(
            )["featureFlags"]
            self.assertEqual(
                feature_flags_for_canonical_distinct_id,
                {
                    "bool-key-overridden-to-true": True,
                    "multivariate-flag-overridden": "third-variant",
                    "multivariate-flag-not-overridden": "second-variant",
                    "flag-rollout-100": True,
                },
            )
        # Ensure we get the same response from both of the user's distinct_ids
        with self.assertNumQueries(3):
            response_non_canonical_distinct_id = self._post_decide(
                api_version=2, distinct_id="not-canonical-distinct-id")
            self.assertEqual(
                response_non_canonical_distinct_id.json()["featureFlags"],
                feature_flags_for_canonical_distinct_id,
            )

        with self.assertNumQueries(3):
            response = self._post_decide(
                api_version=2, distinct_id="user-with-no-overriden-flags")
            self.assertEqual(
                response.json()["featureFlags"],
                {
                    "bool-key-overridden-to-false": True,
                    "multivariate-flag-overridden": "first-variant",
                    "multivariate-flag-not-overridden": "second-variant",
                    "flag-rollout-100": True,
                },
            )

    def test_feature_flags_v2_with_groups(self):
        # More in-depth tests in posthog/api/test/test_feature_flag.py

        self.team.app_urls = ["https://example.com"]
        self.team.save()
        self.client.logout()
        GroupTypeMapping.objects.create(team=self.team,
                                        group_type="organization",
                                        group_type_index=0)
        Person.objects.create(team=self.team,
                              distinct_ids=["example_id"],
                              properties={
                                  "email": "*****@*****.**",
                                  "realm": "cloud"
                              })
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "aggregation_group_type_index": 0,
                "groups": [{
                    "rollout_percentage": 100
                }]
            },
            name="This is a group-based flag",
            key="groups-flag",
            created_by=self.user,
        )

        with self.assertNumQueries(4):
            response = self._post_decide(api_version=2,
                                         distinct_id="example_id")
            self.assertEqual(response.json()["featureFlags"], {})

        with self.assertNumQueries(4):
            response = self._post_decide(api_version=2,
                                         distinct_id="example_id",
                                         groups={"organization": "foo"})
            self.assertEqual(response.json()["featureFlags"],
                             {"groups-flag": True})

    def test_feature_flags_with_personal_api_key(self):
        key = PersonalAPIKey(label="X", user=self.user)
        key.save()
        Person.objects.create(team=self.team, distinct_ids=["example_id"])
        FeatureFlag.objects.create(
            team=self.team,
            rollout_percentage=100,
            name="Test",
            key="test",
            created_by=self.user,
        )
        FeatureFlag.objects.create(
            team=self.team,
            rollout_percentage=100,
            name="Disabled",
            key="disabled",
            created_by=self.user,
            active=False,
        )  # disabled flag
        FeatureFlag.objects.create(
            team=self.team,
            filters={
                "groups": [{
                    "properties": [],
                    "rollout_percentage": None
                }]
            },
            key="default-flag",
            created_by=self.user,
        )  # enabled for everyone
        response = self._post_decide({
            "distinct_id": "example_id",
            "api_key": key.value,
            "project_id": self.team.id
        }).json()
        self.assertEqual(response["featureFlags"], ["test", "default-flag"])

    def test_personal_api_key_without_project_id(self):
        key = PersonalAPIKey(label="X", user=self.user)
        key.save()
        Person.objects.create(team=self.team, distinct_ids=["example_id"])

        response = self._post_decide({
            "distinct_id": "example_id",
            "api_key": key.value
        })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(
            response.json(),
            {
                "type": "authentication_error",
                "code": "invalid_api_key",
                "detail":
                "Project API key invalid. You can find your project API key in PostHog project settings.",
                "attr": None,
            },
        )

    def test_missing_token(self):
        key = PersonalAPIKey(label="X", user=self.user)
        key.save()
        Person.objects.create(team=self.team, distinct_ids=["example_id"])
        FeatureFlag.objects.create(
            team=self.team,
            rollout_percentage=100,
            name="Test",
            key="test",
            created_by=self.user,
        )
        response = self._post_decide({
            "distinct_id": "example_id",
            "api_key": None,
            "project_id": self.team.id
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_json = response.json()
        self.assertEqual(response_json["featureFlags"], [])
        self.assertFalse(response_json["sessionRecording"])

    def test_invalid_payload_on_decide_endpoint(self):

        invalid_payloads = [
            base64.b64encode(b"1-1").decode("utf-8"), "1==1", "{distinct_id-1}"
        ]

        for payload in invalid_payloads:
            response = self.client.post("/decide/", {"data": payload},
                                        HTTP_ORIGIN="http://127.0.0.1:8000")
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
            response_data = response.json()
            detail = response_data.pop("detail")
            self.assertEqual(
                response.json(),
                {
                    "type": "validation_error",
                    "code": "malformed_data",
                    "attr": None
                },
            )
            self.assertIn("Malformed request data:", detail)

    def test_invalid_gzip_payload_on_decide_endpoint(self):

        response = self.client.post(
            "/decide/?compression=gzip",
            data=b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03",
            HTTP_ORIGIN="http://127.0.0.1:8000",
            content_type="text/plain",
        )
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        response_data = response.json()
        detail = response_data.pop("detail")
        self.assertEqual(
            response.json(),
            {
                "type": "validation_error",
                "code": "malformed_data",
                "attr": None
            },
        )
        self.assertIn("Malformed request data:", detail)
class RefundTests(ModuleStoreTestCase):
    """
    Tests for the manual refund page
    """
    def setUp(self):
        super(RefundTests, self).setUp()

        self.course = CourseFactory.create(org='testorg',
                                           number='run1',
                                           display_name='refundable course')
        self.course_id = self.course.location.course_key
        self.client = Client()
        self.admin = UserFactory.create(username='******',
                                        email='*****@*****.**',
                                        password='******')
        SupportStaffRole().add_users(self.admin)
        self.client.login(username=self.admin.username, password='******')

        self.student = UserFactory.create(username='******',
                                          email='*****@*****.**')
        self.course_mode = CourseMode.objects.get_or_create(
            course_id=self.course_id, mode_slug='verified', min_price=1)[0]

        self.order = None
        self.form_pars = {
            'course_id': str(self.course_id),
            'user': self.student.email
        }

    def tearDown(self):
        self.course_mode.delete()
        Order.objects.filter(user=self.student).delete()
        super(RefundTests, self).tearDown()

    def _enroll(self, purchase=True):
        CourseEnrollment.enroll(self.student, self.course_id,
                                self.course_mode.mode_slug)
        if purchase:
            self.order = Order.get_cart_for_user(self.student)
            CertificateItem.add_to_order(self.order, self.course_id, 1,
                                         self.course_mode.mode_slug)
            self.order.purchase()
        self.course_mode.expiration_datetime = datetime.datetime(
            1983, 4, 6, tzinfo=pytz.UTC)
        self.course_mode.save()

    def test_support_access(self):
        response = self.client.get('/support/')
        self.assertTrue(response.status_code, 200)
        self.assertContains(response, 'Manual Refund')
        response = self.client.get('/support/refund/')
        self.assertTrue(response.status_code, 200)

        # users without the permission can't access support
        SupportStaffRole().remove_users(self.admin)
        response = self.client.get('/support/')
        self.assertTrue(response.status_code, 302)

        response = self.client.get('/support/refund/')
        self.assertTrue(response.status_code, 302)

    def test_bad_courseid(self):
        response = self.client.post('/support/refund/', {
            'course_id': 'foo',
            'user': self.student.email
        })
        self.assertContains(response, 'Course id invalid')

    def test_bad_user(self):
        response = self.client.post('/support/refund/', {
            'course_id': str(self.course_id),
            'user': '******'
        })
        self.assertContains(response, 'User not found')

    @patch('student.models.CourseEnrollment.refund_cutoff_date')
    def test_not_refundable(self, cutoff_date):
        self._enroll()
        self.course_mode.expiration_datetime = datetime.datetime(
            2033, 4, 6, tzinfo=pytz.UTC)
        self.course_mode.save()
        cutoff_date.return_value = datetime.datetime.now(
            pytz.UTC) + datetime.timedelta(days=1)
        response = self.client.post('/support/refund/', self.form_pars)
        self.assertContains(response, 'not past the refund window')

    def test_no_order(self):
        self._enroll(purchase=False)
        response = self.client.post('/support/refund/', self.form_pars)
        self.assertContains(response,
                            u'No order found for %s' % self.student.username)

    def test_valid_order(self):
        self._enroll()
        response = self.client.post('/support/refund/', self.form_pars)
        self.assertContains(response, "About to refund this order")
        self.assertContains(response, "enrolled")
        self.assertContains(response, "CertificateItem Status")

    def test_do_refund(self):
        self._enroll()
        pars = self.form_pars
        pars['confirmed'] = 'true'
        response = self.client.post('/support/refund/', pars)
        self.assertTrue(response.status_code, 302)
        response = self.client.get(response.get('location'))

        self.assertContains(response, u"Unenrolled %s from" % self.student)
        self.assertContains(response, "Refunded 1.00 for order id")

        self.assertFalse(
            CourseEnrollment.is_enrolled(self.student, self.course_id))
Exemple #44
0
class TestPhotoVerificationResultsCallback(ModuleStoreTestCase):
    """
    Tests for the results_callback view.
    """
    def setUp(self):
        self.course = CourseFactory.create(org='Robot',
                                           number='999',
                                           display_name='Test Course')
        self.course_id = self.course.id
        self.user = UserFactory.create()
        self.attempt = SoftwareSecurePhotoVerification(status="submitted",
                                                       user=self.user)
        self.attempt.save()
        self.receipt_id = self.attempt.receipt_id
        self.client = Client()

    def mocked_has_valid_signature(method, headers_dict, body_dict, access_key,
                                   secret_key):
        return True

    def test_invalid_json(self):
        """
        Test for invalid json being posted by software secure.
        """
        data = {"Testing invalid"}
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB: testing',
            HTTP_DATE='testdate')
        self.assertIn('Invalid JSON', response.content)
        self.assertEqual(response.status_code, 400)

    def test_invalid_dict(self):
        """
        Test for invalid dictionary being posted by software secure.
        """
        data = '"\\"Test\\tTesting"'
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        self.assertIn('JSON should be dict', response.content)
        self.assertEqual(response.status_code, 400)

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_invalid_access_key(self):
        """
        Test for invalid access key.
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": "Testing",
            "Reason": "Testing",
            "MessageType": "Testing"
        }
        json_data = json.dumps(data)
        response = self.client.post(reverse('verify_student_results_callback'),
                                    data=json_data,
                                    content_type='application/json',
                                    HTTP_AUTHORIZATION='test testing:testing',
                                    HTTP_DATE='testdate')
        self.assertIn('Access key invalid', response.content)
        self.assertEqual(response.status_code, 400)

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_wrong_edx_id(self):
        """
        Test for wrong id of Software secure verification attempt.
        """
        data = {
            "EdX-ID": "Invalid-Id",
            "Result": "Testing",
            "Reason": "Testing",
            "MessageType": "Testing"
        }
        json_data = json.dumps(data)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        self.assertIn('edX ID Invalid-Id not found', response.content)
        self.assertEqual(response.status_code, 400)

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_pass_result(self):
        """
        Test for verification passed.
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": "PASS",
            "Reason": "",
            "MessageType": "You have been verified."
        }
        json_data = json.dumps(data)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        attempt = SoftwareSecurePhotoVerification.objects.get(
            receipt_id=self.receipt_id)
        self.assertEqual(attempt.status, u'approved')
        self.assertEquals(response.content, 'OK!')

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_fail_result(self):
        """
        Test for failed verification.
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": 'FAIL',
            "Reason": 'Invalid photo',
            "MessageType": 'Your photo doesn\'t meet standards.'
        }
        json_data = json.dumps(data)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        attempt = SoftwareSecurePhotoVerification.objects.get(
            receipt_id=self.receipt_id)
        self.assertEqual(attempt.status, u'denied')
        self.assertEqual(attempt.error_code,
                         u'Your photo doesn\'t meet standards.')
        self.assertEqual(attempt.error_msg, u'"Invalid photo"')
        self.assertEquals(response.content, 'OK!')

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_system_fail_result(self):
        """
        Test for software secure result system failure.
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": 'SYSTEM FAIL',
            "Reason": 'Memory overflow',
            "MessageType": 'You must retry the verification.'
        }
        json_data = json.dumps(data)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        attempt = SoftwareSecurePhotoVerification.objects.get(
            receipt_id=self.receipt_id)
        self.assertEqual(attempt.status, u'must_retry')
        self.assertEqual(attempt.error_code,
                         u'You must retry the verification.')
        self.assertEqual(attempt.error_msg, u'"Memory overflow"')
        self.assertEquals(response.content, 'OK!')

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_unknown_result(self):
        """
        test for unknown software secure result
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": 'Unknown',
            "Reason": 'Unknown reason',
            "MessageType": 'Unknown message'
        }
        json_data = json.dumps(data)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        self.assertIn('Result Unknown not understood', response.content)

    @mock.patch('verify_student.ssencrypt.has_valid_signature',
                mock.Mock(side_effect=mocked_has_valid_signature))
    def test_reverification(self):
        """
         Test software secure result for reverification window.
        """
        data = {
            "EdX-ID": self.receipt_id,
            "Result": "PASS",
            "Reason": "",
            "MessageType": "You have been verified."
        }
        window = MidcourseReverificationWindowFactory(course_id=self.course_id)
        self.attempt.window = window
        self.attempt.save()
        json_data = json.dumps(data)
        self.assertEqual(
            CourseEnrollment.objects.filter(course_id=self.course_id).count(),
            0)
        response = self.client.post(
            reverse('verify_student_results_callback'),
            data=json_data,
            content_type='application/json',
            HTTP_AUTHORIZATION='test BBBBBBBBBBBBBBBBBBBB:testing',
            HTTP_DATE='testdate')
        self.assertEquals(response.content, 'OK!')
        self.assertIsNotNone(
            CourseEnrollment.objects.get(course_id=self.course_id))
Exemple #45
0
class ContentConvertionTests(AskbotTestCase):
    def setUp(self):
        self.u1 = self.create_user(username='******')
        self.u1.set_password('password')
        self.u1.set_admin_status()
        self.u1.save()
        self.u2 = self.create_user(username='******')
        self.client = Client()

        #content
        self.question = self.post_question(user=self.u1)
        self.answer_to_convert = self.post_answer(user=self.u2,
                                                  question=self.question)
        self.comment_on_answer = self.post_comment(
            user=self.u1, parent_post=self.answer_to_convert)
        self.another_answer = self.post_answer(user=self.u1,
                                               question=self.question)
        self.comment_to_convert = self.post_comment(
            user=self.u1, parent_post=self.another_answer)

    def test_convert_comment_to_answer(self):
        self.client.login(username='******', password='******')
        old_parent_comment_count = self.another_answer.comment_count
        answer_count = self.question.thread.answer_count
        self.client.post(reverse('comment_to_answer'),
                         {'comment_id': self.comment_to_convert.id})
        converted_answer = self.reload_object(self.comment_to_convert)
        #old_parent = self.another_answer
        old_parent = self.reload_object(self.another_answer)

        #test for convertion
        self.assertEqual(converted_answer.post_type, 'answer')
        #test for parent change
        self.assertNotEqual(old_parent.id, converted_answer.parent.id)
        #test for answer count update
        self.assertEqual(converted_answer.thread.answer_count,
                         answer_count + 1)
        #test for comment count update
        self.assertEqual(old_parent.comment_count,
                         old_parent_comment_count - 1)

        #test the delete post view for errors
        response = self.client.post(reverse('delete_post'), {
            'post_id': converted_answer.id,
            'cancel_vote': 'false'
        },
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertTrue(b'is_deleted' in response.content)

    def test_convert_answer_to_comment(self):
        comment_count = self.question.comment_count
        #because the answer itself has a comment too!
        comment_count += self.answer_to_convert.comment_count

        answer_count = self.question.thread.answer_count
        self.client.login(username='******', password='******')
        self.client.post(reverse('repost_answer_as_comment_under_question'),
                         {'answer_id': self.answer_to_convert.id})
        converted_comment = self.reload_object(self.answer_to_convert)
        old_parent = self.reload_object(self.question)

        #test for convertion
        self.assertEqual(converted_comment.post_type, 'comment')
        #test for answer count update
        self.assertEqual(converted_comment.thread.answer_count,
                         answer_count - 1)
        #test for comment count update
        self.assertEqual(old_parent.comment_count, comment_count + 1)
Exemple #46
0
class TestAPIUser(TransactionTestCase):
    fixtures = ['init_panda.json', 'test_users.json']

    def setUp(self):
        settings.CELERY_ALWAYS_EAGER = True

        self.user = utils.get_panda_user()
        self.panda_user_group = Group.objects.get(name='panda_user')

        self.auth_headers = utils.get_auth_headers()

        self.client = Client()

    def test_get(self):
        response = self.client.get('/api/1.0/user/%i/' % self.user.id,
                                   **self.auth_headers)

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertNotIn('username', body)
        self.assertNotIn('password', body)
        self.assertNotIn('is_superuser', body)
        self.assertNotIn('is_staff', body)

    def test_get_unauthorized(self):
        response = self.client.get('/api/1.0/user/%i/' % self.user.id)

        self.assertEqual(response.status_code, 401)

    def test_list(self):
        response = self.client.get('/api/1.0/user/',
                                   data={'limit': 5},
                                   **self.auth_headers)

        self.assertEqual(response.status_code, 200)

        body = json.loads(response.content)

        self.assertEqual(len(body['objects']), 2)
        self.assertEqual(body['meta']['total_count'], 2)
        self.assertEqual(body['meta']['limit'], 5)
        self.assertEqual(body['meta']['offset'], 0)
        self.assertEqual(body['meta']['next'], None)
        self.assertEqual(body['meta']['previous'], None)

    def test_create_as_admin(self):
        new_user = {
            'email': '*****@*****.**',
            'password': '******',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        response = self.client.post(
            '/api/1.0/user/',
            content_type='application/json',
            data=json.dumps(new_user),
            **utils.get_auth_headers('*****@*****.**'))

        self.assertEqual(response.status_code, 201)

        body = json.loads(response.content)

        self.assertEqual(body['email'], '*****@*****.**')
        self.assertEqual(body['first_name'], 'Testy')
        self.assertEqual(body['last_name'], 'McTester')

        new_user = User.objects.get(username='******')

        self.assertEqual(new_user.username, '*****@*****.**')
        self.assertEqual(new_user.email, '*****@*****.**')
        self.assertEqual(new_user.first_name, 'Testy')
        self.assertEqual(new_user.last_name, 'McTester')
        self.assertNotEqual(new_user.api_key, None)

        self.assertEqual(list(new_user.groups.all()), [self.panda_user_group])

        self.assertEqual(
            authenticate(username='******', password='******'),
            new_user)

    def test_create_as_user(self):
        new_user = {
            'email': '*****@*****.**',
            'password': '******',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        response = self.client.post('/api/1.0/user/',
                                    content_type='application/json',
                                    data=json.dumps(new_user),
                                    **self.auth_headers)

        self.assertEqual(response.status_code, 401)

    def test_update_as_user(self):
        update_user = {
            'email': '*****@*****.**',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        before_user = self.user

        response = self.client.put('/api/1.0/user/%i/' % self.user.id,
                                   content_type='application/json',
                                   data=json.dumps(update_user),
                                   **self.auth_headers)

        self.assertEqual(response.status_code, 202)

        after_user = UserProxy.objects.get(id=self.user.id)

        self.assertEqual(after_user.email, '*****@*****.**')
        self.assertEqual(after_user.username, '*****@*****.**')
        self.assertEqual(after_user.first_name, 'Testy')
        self.assertEqual(after_user.last_name, 'McTester')
        self.assertEqual(before_user.date_joined, after_user.date_joined)
        self.assertEqual(before_user.is_active, after_user.is_active)
        self.assertEqual(before_user.last_login, after_user.last_login)
        self.assertEqual(before_user.password, after_user.password)

    def test_update_as_different_user(self):
        new_user = {
            'email': '*****@*****.**',
            'password': '******',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        response = self.client.post(
            '/api/1.0/user/',
            content_type='application/json',
            data=json.dumps(new_user),
            **utils.get_auth_headers('*****@*****.**'))

        self.assertEqual(response.status_code, 201)

        update_user = {
            'email': '*****@*****.**',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        response = self.client.put(
            '/api/1.0/user/%i/' % self.user.id,
            content_type='application/json',
            data=json.dumps(update_user),
            **utils.get_auth_headers('*****@*****.**'))

        self.assertEqual(response.status_code, 401)

    def test_update_as_admin(self):
        update_user = {
            'email': '*****@*****.**',
            'first_name': 'Testy',
            'last_name': 'McTester'
        }

        before_user = self.user

        response = self.client.put(
            '/api/1.0/user/%i/' % self.user.id,
            content_type='application/json',
            data=json.dumps(update_user),
            **utils.get_auth_headers('*****@*****.**'))

        self.assertEqual(response.status_code, 202)

        after_user = UserProxy.objects.get(id=self.user.id)

        self.assertEqual(after_user.email, '*****@*****.**')
        self.assertEqual(after_user.username, '*****@*****.**')
        self.assertEqual(after_user.first_name, 'Testy')
        self.assertEqual(after_user.last_name, 'McTester')
        self.assertEqual(before_user.date_joined, after_user.date_joined)
        self.assertEqual(before_user.is_active, after_user.is_active)
        self.assertEqual(before_user.last_login, after_user.last_login)
        self.assertEqual(before_user.password, after_user.password)

    def test_change_password(self):
        update_user = {
            'email': '*****@*****.**',
            'first_name': 'Testy',
            'last_name': 'McTester',
            'password': '******'
        }

        before_user = self.user

        response = self.client.put('/api/1.0/user/%i/' % self.user.id,
                                   content_type='application/json',
                                   data=json.dumps(update_user),
                                   **self.auth_headers)

        self.assertEqual(response.status_code, 202)

        after_user = UserProxy.objects.get(id=self.user.id)

        self.assertEqual(after_user.email, '*****@*****.**')
        self.assertEqual(after_user.username, '*****@*****.**')
        self.assertEqual(after_user.first_name, 'Testy')
        self.assertEqual(after_user.last_name, 'McTester')
        self.assertEqual(before_user.date_joined, after_user.date_joined)
        self.assertEqual(before_user.is_active, after_user.is_active)
        self.assertEqual(before_user.last_login, after_user.last_login)
        self.assertNotEqual(before_user.password, after_user.password)
        self.assertNotEqual(after_user.password, 'foobarbaz')
Exemple #47
0
    def testCreateAndEdit(self):

        # Login as user
        client = Client()
        login = client.login(username=self.username, password=self.password)
        self.assertTrue(login)

        ##########
        # Create #
        ##########

        create_url = reverse('tardis.tardis_portal.views.create_experiment')

        # Check the form is accessible
        response = client.get(create_url)
        expect(response.status_code).to_equal(200)

        # Create client and go to account management URL
        data = {'title': 'The Elements',
                'authors': 'Tom Lehrer, Arthur Sullivan',
                'institution_name': 'The University of California',
                'description':
                "There's antimony, arsenic, aluminum, selenium," +
                "And hydrogen and oxygen and nitrogen and rhenium..."
                }
        response = client.post(create_url, data=data)
        # Expect redirect to created experiment
        expect(response.status_code).to_equal(303)
        created_url = response['Location']

        # Check that it redirects to a valid location
        response = client.get(created_url)
        expect(response.status_code).to_equal(200)

        experiment_id = resolve(urlparse(created_url).path)\
            .kwargs['experiment_id']
        experiment = Experiment.objects.get(id=experiment_id)
        for attr in ('title', 'description', 'institution_name'):
            expect(getattr(experiment, attr)).to_equal(data[attr])

        # Check authors were created properly
        expect([a.author for a in experiment.experimentauthor_set.all()])\
            .to_equal(data['authors'].split(', '))

        acl = ObjectACL.objects.get(content_type=experiment.get_ct(),
                                    object_id=experiment.id,
                                    pluginId='django_user',
                                    entityId=self.user.id)
        expect(acl.canRead).to_be_truthy()
        expect(acl.canWrite).to_be_truthy()
        expect(acl.isOwner).to_be_truthy()

        ########
        # Edit #
        ########

        edit_url = reverse('tardis.tardis_portal.views.edit_experiment',
                           kwargs={'experiment_id': str(experiment_id)})

        # Check the form is accessible
        response = client.get(edit_url)
        expect(response.status_code).to_equal(200)

        # Create client and go to account management URL
        data = {'title': 'I Am the Very Model of a Modern Major-General',
                'authors': 'W. S. Gilbert(http://en.wikipedia.org/wiki/'
                'W._S._Gilbert), Arthur Sullivan ([email protected])',
                'institution_name': 'Savoy Theatre',
                'description':
                "I am the very model of a modern Major-General," +
                "I've information vegetable, animal, and mineral,"
                }
        response = client.post(edit_url, data=data)
        # Expect redirect to created experiment
        expect(response.status_code).to_equal(303)
        edit_url = response['Location']

        # Check that it redirects to a valid location
        response = client.get(created_url)
        expect(response.status_code).to_equal(200)

        experiment_id = resolve(urlparse(created_url).path)\
            .kwargs['experiment_id']
        experiment = Experiment.objects.get(id=experiment_id)
        for attr in ('title', 'description', 'institution_name'):
            expect(getattr(experiment, attr)).to_equal(data[attr])

        # Check authors were created properly
        expect([a.author for a in experiment.experimentauthor_set.all()])\
            .to_equal(['W. S. Gilbert', 'Arthur Sullivan'])
        expect([a.url for a in experiment.experimentauthor_set.all()])\
            .to_equal(['http://en.wikipedia.org/wiki/W._S._Gilbert',
                       ''])
        expect([a.email for a in experiment.experimentauthor_set.all()])\
            .to_equal(['',
                       '*****@*****.**'])
Exemple #48
0
class EnvironmentVipPostSuccessTestCase(NetworkApiTestCase):
    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/api_ogp/fixtures/initial_objecttype.json',
        'networkapi/api_ogp/fixtures/initial_objectgrouppermissiongeneral.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/requisicaovips/fixtures/initial_optionsvip.json',
        'networkapi/api_environment_vip/fixtures/initial_base.json',
    ]

    json_path = 'api_environment_vip/tests/sanity/json/post/%s'

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

    def tearDown(self):
        pass

    def test_post_one_env(self):
        """Test of success to post one environment vip."""

        name_file = self.json_path % 'post_one_envvip.json'

        # Does post request
        response = self.client.post(
            '/api/v3/environment-vip/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(201, response.status_code)

        id_env = response.data[0]['id']

        # Does get request
        response = self.client.get(
            '/api/v3/environment-vip/%s/?include=conf' % id_env,
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)

        # Removes property id
        data = response.data
        del data['environments_vip'][0]['id']

        self.compare_json(name_file, data)

    def test_post_one_env_with_environments(self):
        """Test of success to post one environment vip with environments."""

        name_file = self.json_path % 'post_one_envvip_with_environments.json'

        # Does post request
        response = self.client.post(
            '/api/v3/environment-vip/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(201, response.status_code)

        id_env = response.data[0]['id']

        # Does get request
        response = self.client.get(
            '/api/v3/environment-vip/%s/?include=environments,conf' % id_env,
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)

        # Removes property id
        data = response.data
        del data['environments_vip'][0]['id']

        self.compare_json(name_file, data)

    def test_post_one_env_with_optionsvip(self):
        """Test of success to post one environment vip with options vip."""

        name_file = self.json_path % 'post_one_envvip_with_optionsvip.json'

        # Does post request
        response = self.client.post(
            '/api/v3/environment-vip/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(201, response.status_code)

        id_env = response.data[0]['id']

        # Does get request
        response = self.client.get(
            '/api/v3/environment-vip/%s/?include=optionsvip,conf' % id_env,
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)

        # Removes property id
        data = response.data
        del data['environments_vip'][0]['id']

        self.compare_json(name_file, data)
Exemple #49
0
    def test_new_map_config(self):
        """Test that new map config can be properly assigned
        """
        c = Client()
        c.login(username='******', password='******')

        # Test successful new map creation
        m = Map()
        admin_user = User.objects.get(username='******')
        layer_name = Layer.objects.all()[0].typename
        m.create_from_layer_list(admin_user, [layer_name], "title", "abstract")
        map_id = m.id

        c = Client()

        url = reverse('new_map_json')

        # Test GET method with COPY
        response = c.get(url, {'copy': map_id})
        self.assertEquals(response.status_code, 200)
        map_obj = Map.objects.get(id=map_id)
        config_map = map_obj.viewer_json()
        response_config_dict = json.loads(response.content)
        self.assertEquals(config_map['map']['layers'],
                          response_config_dict['map']['layers'])

        # Test GET method no COPY and no layer in params
        response = c.get(url)
        self.assertEquals(response.status_code, 200)
        config_default = default_map_config()[0]
        response_config_dict = json.loads(response.content)
        self.assertEquals(config_default['about']['abstract'],
                          response_config_dict['about']['abstract'])
        self.assertEquals(config_default['about']['title'],
                          response_config_dict['about']['title'])

        # Test GET method no COPY but with layer in params
        response = c.get(url, {'layer': layer_name})
        self.assertEquals(response.status_code, 200)
        response_dict = json.loads(response.content)
        self.assertEquals(response_dict['fromLayer'], True)

        # Test POST method without authentication
        response = c.post(url, {'layer': layer_name})
        self.assertEquals(response.status_code, 401)

        # Test POST method with authentication and a layer in params
        c.login(username='******', password='******')

        response = c.post(url, {'layer': layer_name})
        # Should not accept the request
        self.assertEquals(response.status_code, 400)

        # Test POST method with map data in json format
        response = c.post(url,
                          data=self.viewer_config,
                          content_type="text/json")
        self.assertEquals(response.status_code, 200)
        map_id = int(json.loads(response.content)['id'])

        # Test methods other than GET or POST and no layer in params
        response = c.put(url)
        self.assertEquals(response.status_code, 405)
class UserMapViewTests(TestCase):
    """Class for testing user map view."""
    def setUp(self):
        """Run for each test."""
        self.not_mapped_username = '******'
        self.not_mapped_password = '******'
        self.not_mapped_user = UserFactory.create(
            username=self.not_mapped_username,
            password=self.not_mapped_password)

        self.mapped_username = '******'
        self.mapped_password = '******'
        self.mapped_user = UserFactory.create(username=self.mapped_username,
                                              password=self.mapped_password)
        self.mapped_user_map = UserMapFactory(user=self.mapped_user)

        self.client = Client()

    def test_index(self):
        """Test for index view."""
        response = self.client.get(reverse('user_map:index'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'user_map/data_privacy.html')
        self.assertTemplateUsed(response, 'user_map/index.html')

    def test_index_login_mapped(self):
        """Test for index view after logging in for mapped user."""
        self.assertTrue(
            self.client.login(username=self.mapped_username,
                              password=self.mapped_password))
        response = self.client.get(reverse('user_map:index'))
        self.assertNotContains(response, 'user-menu-add-button')
        self.assertContains(response, 'user-menu-edit-button')

    def test_list_users(self):
        """Test for listing all the users through REST API."""
        response = self.client.get(reverse('user_map:usermap-list'))
        self.assertEqual(response['Content-Type'], 'application/json')
        self.assertContains(response, 'FeatureCollection')
        self.assertContains(response, self.mapped_user.username)

    def test_list_users_with_post(self):
        """Test list user view."""
        response = self.client.post(reverse('user_map:usermap-list'))
        self.assertEqual(response.status_code, 405)  # 405 = not allowed

    def test_add_user_page_without_login(self):
        """Test showing 'add user' page without log in first.

        Should redirect to index page"""
        response = self.client.get(reverse('user_map:add'))
        self.assertRedirects(
            response,
            reverse(LOGIN_VIEW) + '?next=' + reverse('user_map:add'), 302, 200)

    def test_add_user_page_with_unmapped_user(self):
        """Test showing 'add user' view using get."""
        # login with unmapped user
        self.assertTrue(
            self.client.login(username=self.not_mapped_username,
                              password=self.not_mapped_password))
        response = self.client.get(reverse('user_map:add'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'user_map/user_add_update.html')

    def test_add_user_page_with_mapped_user(self):
        """Test accessing 'add user page' with mapped user.

        Should redirect to index page.
        """
        # login with mapped user
        self.assertTrue(
            self.client.login(username=self.mapped_username,
                              password=self.mapped_password))
        response = self.client.get(reverse('user_map:add'))
        self.assertRedirects(response, reverse('user_map:index'), 302, 200)

    def test_add_user_success(self):
        """Test adding user map using post."""
        # login with unmapped user
        self.assertTrue(
            self.client.login(username=self.not_mapped_username,
                              password=self.not_mapped_password))
        response = self.client.post(
            reverse('user_map:add'), {
                'roles':
                '1',
                'location': ('{"type":"Point","coordinates":[22.5,'
                             '-16.63619187839765]}'),
                'image':
                '',
                'csrfmiddlewaretoken':
                u'yxeoT16pTxofWArnbgfAOudInBqAOpyq'
            })
        self.assertRedirects(response, reverse('user_map:index'), 302, 200)

    def test_show_update_page(self):
        """Test showing update user page view."""
        # Login first with mapped user
        self.assertTrue(
            self.client.login(username=self.mapped_username,
                              password=self.mapped_password))

        response = self.client.get(reverse('user_map:update'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'user_map/user_add_update.html')

    def test_update_user(self):
        """Test update user."""
        # Login first with mapped user
        self.assertTrue(
            self.client.login(username=self.mapped_username,
                              password=self.mapped_password))

        form_content = dict({
            'roles':
            '1',
            'location': ('{"type":"Point","coordinates":[22.5,'
                         '-16.63619187839765]}'),
            # 'image': 'john/doe/cool.png',
            'csrfmiddlewaretoken':
            u'yxeoT16pTxofWArnbgfAOudInBqAOpyq'
        })
        response = self.client.post(reverse('user_map:update'), form_content)
        self.assertRedirects(response, reverse('user_map:index'), 302, 200)
        user_map = UserMap.objects.get(user=self.mapped_user)
        new_point = Point(22.5, -16.63619187839765)
        self.assertAlmostEqual(user_map.location.x, new_point.x)
        self.assertAlmostEqual(user_map.location.y, new_point.y)
Exemple #51
0
class Skeleton_Test(LiveServerTestCase):
    @set_users()
    def setUp(self):
        self.c = Client()
        self.c.login(username='******', password='******')

    def test_list(self):
        """Get skeleton list."""
        url = reverse('skeleton list')
        r = self.c.get(url)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)

    def test_add(self):
        """
        Test to get skeleton form.
        Simulate it in POST method.
        Test to get new skeleton.
        """
        # Test to get form
        url = reverse('skeleton add')
        r = self.c.get(url)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)
        # Test to add
        POST = {
            'name': 'test skeleton',
            'plugin_pattern': '.',
            'source_pattern': '.'
        }
        r = self.c.post(url, POST)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)
        skeleton = Skeleton.objects.get(name='test skeleton')
        # Test to get
        skeleton = Skeleton.objects.get(pk=skeleton.pk)
        url = reverse('skeleton', args=[skeleton.id])
        r = self.c.get(url)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)

    def test_get(self):
        """Get a skeleton."""
        skeleton = Skeleton.objects.create(name='test skeleton',
                                           plugin_pattern='.',
                                           source_pattern='.')
        url = reverse('skeleton', args=[skeleton.id])
        r = self.c.get(url)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)

    def test_update(self):
        """
        Simulate a POST which change a skeleton.
        Test to see if comment has changed.
        """
        skeleton = Skeleton.objects.create(name='test skeleton',
                                           plugin_pattern='.',
                                           source_pattern='.')
        # Test to update
        url = reverse('skeleton update', args=[skeleton.id])
        POST = skeleton.__dict__
        POST.update({'name': 'test skeleton'})
        r = self.c.post(url, POST)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)
        # Test if updated
        skeleton = Skeleton.objects.get(pk=skeleton.pk)
        self.assertEqual(skeleton.name, 'test skeleton',
                         'Name is not changed (%s).' % skeleton.name)

    def test_delete(self):
        """Test to delete skeleton and if can't get it."""
        skeleton = Skeleton.objects.create(name='test skeleton',
                                           plugin_pattern='.',
                                           source_pattern='.')
        skeleton_id = skeleton.id
        # Test to delete
        url = reverse('skeleton delete', args=[skeleton_id])
        r = self.c.post(url)
        self.assertEqual(r.status_code, 200,
                         "Bad response code (%i)." % r.status_code)

        # Test to get it
        url = reverse('skeleton', args=[skeleton_id])
        r = self.c.get(url)
        self.assertEqual(r.status_code, 404,
                         "Bad response code (%i)." % r.status_code)
Exemple #52
0
class CreateReadUpdateDeleteSurveyDraftsTests(TestCase):
    def setUp(self):
        test_user_credentials = {'username': '******', 'password': '******'}
        if User.objects.count() is 0:
            new_user = User(username=test_user_credentials['username'], email="*****@*****.**")
            new_user.set_password(test_user_credentials['password'])
            new_user.save()
        self.anonymousClient = Client()

        self.user = User.objects.all()[0]
        self.client = Client()
        self.client.post('/accounts/login/', test_user_credentials)

    def post_survey(self, client, survey={}):
        survey_dict = {u'name': "Test Form",
                        u'body': 'body',
                        u'description': 'description'}
        survey_dict.update(survey)
        return self.client.post('/api/survey_drafts', json.dumps(survey_dict), \
                                content_type='application/json')

    def post_asset(self, client, survey={}):
        survey_dict = {u'name': "Test Form",
                        u'body': 'body',
                        u'asset_type': 'question'}
        survey_dict.update(survey)
        return self.client.post('/api/library_assets', json.dumps(survey_dict), \
                                content_type='application/json')

    def test_anonymous_list(self):
        resp = self.anonymousClient.get('/api/survey_drafts')
        self.assertEqual(resp.status_code, 403)

    def test_empty_list(self):
        resp = self.client.get('/api/survey_drafts')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(resp.data), 0)

        self.post_survey(self.client)
        resp2 = self.client.get('/api/survey_drafts')
        self.assertEqual(len(resp2.data), 1)

    def test_retrieve_survey(self):
        self.post_survey(self.client)

        resp = self.client.get('/api/survey_drafts')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.data[0]['id'], 1)

        resp = self.client.get('/api/survey_drafts/1')
        self.assertEqual(resp.data.get('id'), 1)

    def test_patch_survey(self):
        def make_body(question_label):
            return """survey,,,\n,type,name,label\n,text,q1,%s""" % question_label
        self.post_survey(self.client, {
            u'body': make_body("Question1")
        })
        resp = self.client.get('/api/survey_drafts')
        self.assertEqual(resp.data[0]['id'], 1)
        resp2 = self.client.patch('/api/survey_drafts/1', json.dumps({
            u'body': make_body("Question2")
        }), content_type='application/json')
        self.assertEqual(SurveyDraft.objects.get(id=1).body, make_body("Question2"))

    def test_library_assets(self):
        # post a library_asset (question)
        resp = self.client.get('/api/library_assets')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(resp.data.get('results')), 0)

        # ensure library_assets was incremented
        self.post_survey(self.client, {u'asset_type': 'question'})
        resp = self.client.get('/api/library_assets')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(resp.data.get('results')), 1)

        # ensure that survey_drafts was not incremented
        resp = self.client.get('/api/survey_drafts')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(resp.data), 0)

    def test_patch_asset(self):
        def make_body(question_label):
            return """survey,,,\n,type,name,label\n,text,q1,%s""" % question_label
        self.post_asset(self.client, {
            u'body': make_body("Question1")
        })
        resp = self.client.get('/api/library_assets')
        self.assertEqual(resp.data.get('results')[0]['id'], 1)
        resp2 = self.client.patch('/api/library_assets/1', json.dumps({
            u'body': make_body("Question2"),
            u'asset_type':'question'
        }), content_type='application/json')
        self.assertEqual(SurveyDraft.objects.get(id=1).body, make_body("Question2"))

    def test_library_assets_get_loaded_in_correct_order(self):
        def make_body(question_label):
            return """survey,,,\n,type,name,label\n,text,q1,%s""" % question_label

        self.post_asset(self.client, {
            u'body': make_body("Question1"),
            u'asset_type': 'question'
        })

        self.post_asset(self.client, {
            u'body': make_body("Question2"),
            u'asset_type': 'question'
        })

        self.post_asset(self.client, {
            u'body': make_body("Question3"),
            u'asset_type': 'question'
        })

        resp = self.client.get('/api/library_assets')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(resp.data.get('results')), 3)

        self.assertEqual(resp.data.get('results')[0].get('body'), make_body("Question3"))
        self.assertEqual(resp.data.get('results')[1].get('body'), make_body("Question2"))
        self.assertEqual(resp.data.get('results')[2].get('body'), make_body("Question1"))
Exemple #53
0
class TestPosts(TestCase):
    def setUp(self):
        self.client_ano = Client()
        self.client_log = Client()

        self.anonim_user_name = 'anonim_user'
        self.anonim_user = User.objects.create_user(self.anonim_user_name,
                                                    '*****@*****.**',
                                                    'test_user_2020')

        self.login_user_name = 'login_user'
        self.login_user = User.objects.create_user(self.login_user_name,
                                                   '*****@*****.**',
                                                   'test_user_2020')
        self.client_log.force_login(self.login_user)

    def test_personal_page(self):
        """Проверяет создание страницы нового пользователя."""

        # Переход на страницу тестового пользователя
        response = self.client_log.get(reverse('profile',
                                               args=[self.login_user_name]),
                                       follow=True)
        self.assertEqual(response.status_code, 200, msg='Userpage not found!')

    def test_create_new_post_by_login_user(self):
        """ Проверяет что авторизованный
        пользователь может опубликовать пост.
        """

        post_text = 'New TEXT !!!'
        response = self.client_log.post(reverse('new_post'), {
            'text': post_text,
            'author': self.login_user_name
        },
                                        follow=True)

        count = Post.objects.filter(author=self.login_user.id).count()
        self.assertEqual(1, count, msg='Пост не опубликован')
        self.assertRedirects(response, '/')

    def test_create_new_post_by_anonim_user(self):
        """Проверяет что неавторизованный пользователь
        не может опубликовать пост.
        """

        response = self.client_ano.post(reverse('new_post'), {
            'text': 'New TEXT !!!',
            'author': self.anonim_user.username
        },
                                        follow=True)
        login = '******'
        new_post = 'new_post'
        url = (f'{reverse(login)}?next={reverse(new_post)}')
        self.assertRedirects(response, url)

        count = Post.objects.filter(author=self.anonim_user.id).count()
        self.assertEqual(0,
                         count,
                         msg='Создан пост неавторизованным пользователем')

    def test_check_new_post_on_pages(self):
        """Проверяет наличее созданного пост на страницах:
        Index, Post, Profile
        """

        post_text = 'New TEXT !!!'
        self.client_log.post(reverse('new_post'), {
            'text': post_text,
            'author': self.login_user_name
        },
                             follow=False)
        self.check_correct_text_on_pages(post_text)

    def test_login_user_can_edit_his_post(self):
        """Проверяет что залогиненый пользователь может отредактирвать свой пост.
        Изменения будут везде.
        """

        post_text = 'New TEXT !!!'
        edit_post_text = 'edit TEXT !!!'

        self.client_log.post(reverse('new_post'), {
            'text': post_text,
            'author': self.login_user_name
        },
                             follow=False)

        self.client_log.post(reverse('post_edit',
                                     args=[self.login_user_name, 1]), {
                                         'text': edit_post_text,
                                         'author': self.login_user_name
                                     },
                             follow=False)

        self.check_correct_text_on_pages(edit_post_text)

    def check_correct_text_on_pages(self, text_to_find):
        """Проверяет страницы 'insex', 'profile', 'post'
        на наличее поста с указанным текстом.
        """
        cache.clear()
        # Check post on the index page:
        response = self.client_log.get(reverse('index'))

        self.assertEqual(text_to_find,
                         response.context['page'].object_list[0].text,
                         msg='Нет записи с текстом на странице index')

        # Check post on the prifile page:
        response = self.client_log.get(
            reverse('profile', args=[self.login_user_name]))
        self.assertEqual(text_to_find,
                         response.context['page'].object_list[0].text,
                         msg='Нет записи с текстом на странице prifile')

        # Check post on the prifile/id/ page:
        response = self.client_log.get(
            reverse('post', args=[self.login_user_name, 1]))
        post = response.context['post']
        self.assertEqual(text_to_find,
                         post.text,
                         msg='Нет записи с текстом на стр. prifile/post_id')
Exemple #54
0
class RefundableTest(SharedModuleStoreTestCase):
    """
    Tests for dashboard utility functions
    """
    USER_PASSWORD = '******'
    ORDER_NUMBER = 'EDX-100000'

    @classmethod
    def setUpClass(cls):
        super(RefundableTest, cls).setUpClass()
        cls.course = CourseFactory.create()

    def setUp(self):
        """ Setup components used by each refund test."""
        super(RefundableTest, self).setUp()
        self.user = UserFactory.create(password=self.USER_PASSWORD)
        self.verified_mode = CourseModeFactory.create(
            course_id=self.course.id,
            mode_slug='verified',
            mode_display_name='Verified',
            expiration_datetime=datetime.now(pytz.UTC) + timedelta(days=1))

        self.enrollment = CourseEnrollment.enroll(self.user,
                                                  self.course.id,
                                                  mode='verified')

        self.client = Client()
        cache.clear()

    @patch(
        'common.djangoapps.student.models.CourseEnrollment.refund_cutoff_date')
    def test_refundable(self, cutoff_date):
        """ Assert base case is refundable"""
        cutoff_date.return_value = datetime.now(pytz.UTC) + timedelta(days=1)
        self.assertTrue(self.enrollment.refundable())

    @patch(
        'common.djangoapps.student.models.CourseEnrollment.refund_cutoff_date')
    def test_refundable_expired_verification(self, cutoff_date):
        """ Assert that enrollment is refundable if course mode has expired."""
        cutoff_date.return_value = datetime.now(pytz.UTC) + timedelta(days=1)
        self.verified_mode.expiration_datetime = datetime.now(
            pytz.UTC) - timedelta(days=1)
        self.verified_mode.save()
        self.assertTrue(self.enrollment.refundable())

    @patch(
        'common.djangoapps.student.models.CourseEnrollment.refund_cutoff_date')
    def test_refundable_when_certificate_exists(self, cutoff_date):
        """ Assert that enrollment is not refundable once a certificat has been generated."""

        cutoff_date.return_value = datetime.now(pytz.UTC) + timedelta(days=1)

        self.assertTrue(self.enrollment.refundable())

        GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='verified')

        self.assertFalse(self.enrollment.refundable())
        self.assertFalse(
            self.enrollment.refundable(
                user_already_has_certs_for=GeneratedCertificate.
                course_ids_with_certs_for_user(self.user)))

        # Assert that can_refund overrides this and allows refund
        self.enrollment.can_refund = True
        self.assertTrue(self.enrollment.refundable())
        self.assertTrue(
            self.enrollment.refundable(
                user_already_has_certs_for=GeneratedCertificate.
                course_ids_with_certs_for_user(self.user)))

    @patch(
        'common.djangoapps.student.models.CourseEnrollment.refund_cutoff_date')
    def test_refundable_with_cutoff_date(self, cutoff_date):
        """ Assert enrollment is refundable before cutoff and not refundable after."""
        cutoff_date.return_value = datetime.now(pytz.UTC) + timedelta(days=1)
        self.assertTrue(self.enrollment.refundable())

        cutoff_date.return_value = datetime.now(
            pytz.UTC) - timedelta(minutes=5)
        self.assertFalse(self.enrollment.refundable())

        cutoff_date.return_value = datetime.now(
            pytz.UTC) + timedelta(minutes=5)
        self.assertTrue(self.enrollment.refundable())

    @ddt.data(
        (timedelta(days=1), timedelta(days=2), timedelta(days=2), 14),
        (timedelta(days=2), timedelta(days=1), timedelta(days=2), 14),
        (timedelta(days=1), timedelta(days=2), timedelta(days=2), 1),
        (timedelta(days=2), timedelta(days=1), timedelta(days=2), 1),
    )
    @ddt.unpack
    @httpretty.activate
    @override_settings(ECOMMERCE_API_URL=TEST_API_URL)
    def test_refund_cutoff_date(self, order_date_delta, course_start_delta,
                                expected_date_delta, days):
        """
        Assert that the later date is used with the configurable refund period in calculating the returned cutoff date.
        """
        now = datetime.now(pytz.UTC).replace(microsecond=0)
        order_date = now + order_date_delta
        course_start = now + course_start_delta
        expected_date = now + expected_date_delta
        refund_period = timedelta(days=days)
        date_placed = order_date.strftime(ECOMMERCE_DATE_FORMAT)
        expected_content = '{{"date_placed": "{date}"}}'.format(
            date=date_placed)

        httpretty.register_uri(httpretty.GET,
                               '{url}/orders/{order}/'.format(
                                   url=TEST_API_URL, order=self.ORDER_NUMBER),
                               status=200,
                               body=expected_content,
                               adding_headers={'Content-Type': JSON})

        self.enrollment.course_overview.start = course_start
        self.enrollment.attributes.create(enrollment=self.enrollment,
                                          namespace='order',
                                          name='order_number',
                                          value=self.ORDER_NUMBER)

        with patch(
                'common.djangoapps.student.models.EnrollmentRefundConfiguration.current'
        ) as config:
            instance = config.return_value
            instance.refund_window = refund_period
            self.assertEqual(self.enrollment.refund_cutoff_date(),
                             expected_date + refund_period)

            expected_date_placed_attr = {
                "namespace": "order",
                "name": "date_placed",
                "value": date_placed,
            }

            self.assertIn(
                expected_date_placed_attr,
                CourseEnrollmentAttribute.get_enrollment_attributes(
                    self.enrollment))

    def test_refund_cutoff_date_no_attributes(self):
        """ Assert that the None is returned when no order number attribute is found."""
        self.assertIsNone(self.enrollment.refund_cutoff_date())

    @patch('openedx.core.djangoapps.commerce.utils.ecommerce_api_client')
    def test_refund_cutoff_date_with_date_placed_attr(
            self, mock_ecommerce_api_client):
        """
        Assert that the refund_cutoff_date returns order placement date if order:date_placed
        attribute exist without calling ecommerce.
        """
        now = datetime.now(pytz.UTC).replace(microsecond=0)
        order_date = now + timedelta(days=2)
        course_start = now + timedelta(days=1)

        self.enrollment.course_overview.start = course_start
        self.enrollment.attributes.create(
            enrollment=self.enrollment,
            namespace='order',
            name='date_placed',
            value=order_date.strftime(ECOMMERCE_DATE_FORMAT))

        refund_config = EnrollmentRefundConfiguration.current()
        self.assertEqual(self.enrollment.refund_cutoff_date(),
                         order_date + refund_config.refund_window)
        mock_ecommerce_api_client.assert_not_called()

    @httpretty.activate
    @override_settings(ECOMMERCE_API_URL=TEST_API_URL)
    def test_multiple_refunds_dashbaord_page_error(self):
        """ Order with mutiple refunds will not throw 500 error when dashboard page will access."""
        now = datetime.now(pytz.UTC).replace(microsecond=0)
        order_date = now + timedelta(days=1)
        expected_content = '{{"date_placed": "{date}"}}'.format(
            date=order_date.strftime(ECOMMERCE_DATE_FORMAT))

        httpretty.register_uri(httpretty.GET,
                               '{url}/orders/{order}/'.format(
                                   url=TEST_API_URL, order=self.ORDER_NUMBER),
                               status=200,
                               body=expected_content,
                               adding_headers={'Content-Type': JSON})

        # creating multiple attributes for same order.
        for attribute_count in range(2):  # pylint: disable=unused-variable
            self.enrollment.attributes.create(enrollment=self.enrollment,
                                              namespace='order',
                                              name='order_number',
                                              value=self.ORDER_NUMBER)

        self.client.login(username=self.user.username,
                          password=self.USER_PASSWORD)
        resp = self.client.post(reverse('dashboard', args=[]))
        self.assertEqual(resp.status_code, 200)
def test_login_invalid_credentials(app: Client, user: dict):
    response = app.post('/expenses-manager/login/', user)
    assert response.status_code == 200
    assert 'Invalid credentials' in response.context['form'].non_field_errors()
Exemple #56
0
class PostFeedbackAPITest(TestCase):
    def setUp(self):
        super(PostFeedbackAPITest, self).setUp()
        # Make sure the unit tests aren't papering over CSRF issues.
        self.client = Client(enforce_csrf_checks=True)

    def test_minimal(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        feedback = models.Response.objects.latest(field_name='id')
        eq_(feedback.happy, True)
        eq_(feedback.description, data['description'])
        eq_(feedback.product, data['product'])

        # Fills in defaults
        eq_(feedback.url, u'')
        eq_(feedback.api, 1)
        eq_(feedback.user_agent, u'')

    def test_maximal(self):
        """Tests an API call with all possible data"""
        data = {
            'happy': True,
            'description': u'Great!',
            'category': u'ui',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
            'url': 'http://example.com/',
            'manufacturer': 'OmniCorp',
            'device': 'OmniCorp',
            'country': 'US',
            'user_agent':
            ('Mozilla/5.0 (Mobile; rv:18.0) Gecko/18.0 Firefox/18.0'),
            'source': 'email',
            'campaign': 'email_test',
        }

        # This makes sure the test is up-to-date. If we add fields
        # to the serializer, then this will error out unless we've
        # also added them to this test.
        for field in models.PostResponseSerializer.base_fields.keys():
            assert field in data, '{0} not in data'.format(field)

        # Post the data and then make sure everything is in the
        # resulting Response. In most cases, the field names line up
        # between PostResponseSerializer and Response with the
        # exception of 'email' which is stored in a different table.
        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        feedback = models.Response.objects.latest(field_name='id')
        for field in models.PostResponseSerializer.base_fields.keys():
            if field == 'email':
                email = models.ResponseEmail.objects.latest(field_name='id')
                eq_(email.email, data['email'])
            else:
                eq_(getattr(feedback, field), data[field])

    def test_with_email(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        feedback = models.Response.objects.latest(field_name='id')
        eq_(feedback.happy, True)
        eq_(feedback.description, data['description'])
        eq_(feedback.platform, data['platform'])
        eq_(feedback.product, data['product'])
        eq_(feedback.channel, data['channel'])
        eq_(feedback.version, data['version'])

        # Fills in defaults
        eq_(feedback.url, u'')
        eq_(feedback.user_agent, u'')
        eq_(feedback.api, 1)

        email = models.ResponseEmail.objects.latest(field_name='id')
        eq_(email.email, data['email'])

    def test_with_context(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
            'slopmenow': 'bar'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        context = models.ResponseContext.objects.latest(field_name='id')
        eq_(context.data, {'slopmenow': 'bar'})

    def test_with_context_truncate_key(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
            'foo012345678901234567890': 'bar'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        context = models.ResponseContext.objects.latest(field_name='id')
        eq_(context.data, {'foo01234567890123456': 'bar'})

    def test_with_context_truncate_value(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
            'foo': ('a' * 100) + 'b'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        context = models.ResponseContext.objects.latest(field_name='id')
        eq_(context.data, {'foo': ('a' * 100)})

    def test_with_context_20_pairs(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
        }

        for i in range(25):
            data['foo%02d' % i] = str(i)

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        context = models.ResponseContext.objects.latest(field_name='id')
        data = sorted(context.data.items())
        eq_(len(data), 20)
        eq_(data[0], ('foo00', '0'))
        eq_(data[-1], ('foo19', '19'))

    def test_null_device_returns_400(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'device': None
        }

        r = self.client.post(reverse('feedback-api'),
                             json.dumps(data),
                             content_type='application/json')
        eq_(r.status_code, 400)
        assert 'device' in r.content

    def test_invalid_email_address_returns_400(self):
        data = {
            'happy': True,
            'description': u'Great!',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': 'foo@example'
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 400)
        assert 'email' in r.content

    # TODO: django-rest-framework 2.3.6 has a bug where BooleanField
    # has a default value of False, so "required=True" has no
    # effect. We really want to require that, so we'll have to wait
    # for a bug fix or something.
    #
    # def test_missing_happy_returns_400(self):
    #     data = {
    #         'description': u'Great!',
    #         'version': u'1.1',
    #         'platform': u'Firefox OS',
    #         'locale': 'en-US',
    #     }
    #
    #     r = self.client.post(reverse('feedback-api'), data)
    #     eq_(r.status_code, 400)
    #     assert 'happy' in r.content

    def test_missing_description_returns_400(self):
        data = {
            'happy': True,
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 400)
        assert 'description' in r.content

    def test_missing_product_returns_400(self):
        data = {
            'happy': True,
            'channel': u'stable',
            'version': u'1.1',
            'description': u'Great!',
            'platform': u'Firefox OS',
            'locale': 'en-US',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 400)
        assert 'product' in r.content

    def test_invalid_product_returns_400(self):
        data = {
            'happy': True,
            'channel': u'stable',
            'version': u'1.1',
            'description': u'Great!',
            'product': u'Nurse Kitty',
            'platform': u'Firefox OS',
            'locale': 'en-US',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 400)
        assert 'product' in r.content

    def test_url_max_length(self):
        url_base = 'http://example.com/'

        # Up to 199 characters is fine.
        data = {
            'happy': True,
            'channel': u'stable',
            'version': u'1.1',
            'description': u'Great! 199',
            'product': u'Firefox OS',
            'platform': u'Firefox OS',
            'url': url_base + ('a' * (199 - len(url_base))) + 'b',
            'locale': 'en-US',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        # 200th character is not fine.
        data = {
            'happy': True,
            'channel': u'stable',
            'version': u'1.1',
            'description': u'Great! 200',
            'product': u'Firefox OS',
            'platform': u'Firefox OS',
            'url': url_base + ('a' * (200 - len(url_base))) + 'b',
            'locale': 'en-US',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 400)

    def test_valid_urls(self):
        test_data = [
            'example.com', 'example.com:80', 'example.com:80/foo',
            'http://example.com', 'http://example.com/foo',
            'http://example.com:80', 'http://example.com:80/foo',
            'https://example.com', 'https://example.com/foo',
            'https://example.com:80', 'https://example.com:80/foo',
            'ftp://example.com', 'about:mozilla', 'chrome://foo'
        ]
        for url in test_data:
            data = {
                'happy': True,
                'channel': u'stable',
                'version': u'1.1',
                'description': u'Great!',
                'product': u'Firefox OS',
                'platform': u'Firefox OS',
                'url': url,
                'locale': 'en-US',
            }

            r = self.client.post(reverse('feedback-api'), data)
            eq_(r.status_code,
                201,
                msg=('%s != 201 (%s)' % (r.status_code, url)))

            get_cache('default').clear()

    def test_user_agent_inferred_bits(self):
        """Tests that we infer the right bits from the user-agent"""
        data = {
            'happy': True,
            'description': u'Great!',
            'category': u'ui',
            'product': u'Firefox OS',
            'channel': u'stable',
            'version': u'1.1',
            'platform': u'Firefox OS',
            'locale': 'en-US',
            'email': '*****@*****.**',
            'url': 'http://example.com/',
            'manufacturer': 'OmniCorp',
            'device': 'OmniCorp',
            'country': 'US',
            'user_agent':
            ('Mozilla/5.0 (Mobile; rv:18.0) Gecko/18.0 Firefox/18.0'),
            'source': 'email',
            'campaign': 'email_test',
        }

        r = self.client.post(reverse('feedback-api'), data)
        eq_(r.status_code, 201)

        feedback = models.Response.objects.latest(field_name='id')
        eq_(feedback.browser, u'Firefox OS')
        eq_(feedback.browser_version, u'1.0')
        eq_(feedback.browser_platform, u'Firefox OS')
Exemple #57
0
class ProjectsAPITest(TestCase):
    "Projects functional tests for api"
    username = "******"
    password = "******"
    prepared = False
    authentication_headers = {
        "CONTENT_TYPE": "application/json",
        "HTTP_AUTHORIZATION": "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk"
    }
    content_type = 'application/json'

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()
            User.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='api_test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='api_test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()

            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='api_test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='api_test',
                                   contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.project = Project(name='api_test',
                                   manager=self.contact,
                                   client=self.contact)
            self.project.set_default_user()
            self.project.save()

            self.status = TaskStatus(name='api_test')
            self.status.set_default_user()
            self.status.save()

            self.milestone = Milestone(name='api_test',
                                       project=self.project,
                                       status=self.status)
            self.milestone.set_default_user()
            self.milestone.save()

            self.task = Task(name='api_test',
                             project=self.project,
                             status=self.status,
                             priority=3)
            self.task.set_default_user()
            self.task.save()

            self.time_slot = TaskTimeSlot(task=self.task,
                                          details='api_test',
                                          time_from=datetime.now(),
                                          user=self.user.get_profile())
            self.time_slot.set_default_user()
            self.time_slot.save()

            self.parent = Project(name='api_test')
            self.parent.set_default_user()
            self.parent.save()

            self.parent_task = Task(name='api_test',
                                    project=self.project,
                                    status=self.status,
                                    priority=3)
            self.parent_task.set_default_user()
            self.parent_task.save()

            self.client = Client()

            self.prepared = True

    def test_unauthenticated_access(self):
        "Test index page at /projects"
        response = self.client.get('/api/projects/projects')
        # Redirects as unauthenticated
        self.assertEquals(response.status_code, 401)

    # Get info about projects, milestones, status, tasks, tasktimes.

    def test_get_project_list(self):
        """ Test index page api/projects """
        response = self.client.get(path=reverse('api_projects'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_status_list(self):
        """ Test index page api/status """
        response = self.client.get(path=reverse('api_projects_status'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_milestones_list(self):
        """ Test index page api/milestones """
        response = self.client.get(path=reverse('api_projects_milestones'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_task_list(self):
        """ Test index page api/tasks """
        response = self.client.get(path=reverse('api_projects_tasks'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_tasktimes_list(self):
        """ Test index page api/tasktimes """
        response = self.client.get(path=reverse('api_projects_tasktimes'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_project(self):
        response = self.client.get(
            reverse('api_projects', kwargs={'object_ptr': self.project.id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['id'], self.project.id)
        self.assertEquals(data['name'], self.project.name)
        self.assertEquals(data['details'], self.project.details)

    def test_get_status(self):
        response = self.client.get(
            reverse('api_projects_status',
                    kwargs={'object_ptr': self.status.id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['id'], self.status.id)
        self.assertEquals(data['name'], self.status.name)

    def test_get_milestone(self):
        response = self.client.get(
            reverse('api_projects_milestones',
                    kwargs={'object_ptr': self.milestone.id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['id'], self.milestone.id)
        self.assertEquals(data['name'], self.milestone.name)
        self.assertEquals(data['project']['id'], self.milestone.project.id)
        self.assertEquals(data['status']['id'], self.milestone.status.id)

    def test_get_task(self):
        response = self.client.get(
            reverse('api_projects_tasks', kwargs={'object_ptr': self.task.id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['id'], self.task.id)
        self.assertEquals(data['name'], self.task.name)
        self.assertEquals(data['priority'], self.task.priority)
        self.assertEquals(data['project']['id'], self.task.project.id)
        self.assertEquals(data['status']['id'], self.task.status.id)

    def test_get_timeslot(self):
        response = self.client.get(
            reverse('api_projects_tasktimes',
                    kwargs={'object_ptr': self.time_slot.id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['id'], self.time_slot.id)
        self.assertEquals(data['task']['id'], self.time_slot.task.id)

    # Common test

    def test_common_project(self):

        #create new project
        new_project = {'name': 'api test', 'details': '<p>test details</p>'}
        response = self.client.post(reverse('api_projects'),
                                    data=json.dumps(new_project),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        #print response.request
        self.assertEquals(response.status_code, 200)

        # check data in response
        data = json.loads(response.content)
        self.assertEquals(data['name'], new_project['name'])
        self.assertEquals(data['details'], new_project['details'])
        project_id = data['id']

        #get info about new project
        response = self.client.get(path=reverse(
            'api_projects', kwargs={'object_ptr': project_id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        #get statuses list
        response = self.client.get(path=reverse('api_projects_status'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        statuses = json.loads(response.content)
        fstatus = statuses[0]['id']

        #create new task status
        new_status = {
            'name': 'Open api test',
            'active': True,
            'hidden': False,
            'details': '<p>test details</p>'
        }
        response = self.client.post(reverse('api_projects_status'),
                                    data=json.dumps(new_status),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], new_status['name'])
        self.assertEquals(data['active'], new_status['active'])
        self.assertEquals(data['hidden'], new_status['hidden'])
        self.assertEquals(data['details'], new_status['details'])
        sstatus = data['id']

        #create new milestone
        new_milestone = {
            'name': 'api test milestone',
            'status': fstatus,
            'project': project_id,
            'start_date': '2011-06-09 12:00:00',
            'details': '<p>test details</p>'
        }
        response = self.client.post(reverse('api_projects_milestones'),
                                    data=json.dumps(new_milestone),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], new_milestone['name'])
        self.assertEquals(data['status']['id'], new_milestone['status'])
        self.assertEquals(data['project']['id'], new_milestone['project'])
        self.assertEquals(data['details'], new_milestone['details'])
        milestone_id = data['id']

        #  create new task
        new_task = {
            'name': 'api test task',
            'status': sstatus,
            'project': project_id,
            'milestone': milestone_id,
            'priority': 5,
            'start_date': '2011-06-02 12:00:00',
            'estimated_time': 5000,
            'details': '<p>test details</p>'
        }
        response = self.client.post(reverse('api_projects_tasks'),
                                    data=json.dumps(new_task),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], new_task['name'])
        self.assertEquals(data['priority'], new_task['priority'])
        self.assertEquals(data['status']['id'], new_task['status'])
        self.assertEquals(data['project']['id'], new_task['project'])
        self.assertEquals(data['milestone']['id'], new_task['milestone'])
        self.assertEquals(data['estimated_time'], new_task['estimated_time'])
        self.assertEquals(data['details'], new_task['details'])
        task_id = data['id']

        #create new subtask
        new_sub_task = {
            'name': 'api test task',
            'status': sstatus,
            'parent': task_id,
            'project': project_id,
            'priority': 5,
            'start_date': '2011-06-02 13:00:00',
            'estimated_time': 2500,
            'details': '<p>test details</p>'
        }

        response = self.client.post(reverse('api_projects_tasks'),
                                    data=json.dumps(new_sub_task),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], new_sub_task['name'])
        self.assertEquals(data['priority'], new_sub_task['priority'])
        self.assertEquals(data['status']['id'], new_sub_task['status'])
        self.assertEquals(data['parent']['id'], new_sub_task['parent'])
        self.assertEquals(data['project']['id'], new_sub_task['project'])
        self.assertEquals(data['estimated_time'],
                          new_sub_task['estimated_time'])
        self.assertEquals(data['details'], new_sub_task['details'])
        sub_task_id = data['id']

        #create task time
        new_tasktime = {
            'task': task_id,
            'minutes': 400,
            'details': '<p>test details</p>'
        }

        response = self.client.post(reverse('api_projects_tasktimes'),
                                    data=json.dumps(new_tasktime),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['task']['id'], new_tasktime['task'])
        self.assertEquals(data['details'], new_tasktime['details'])
        tasktime_id = data['id']

        #start task time
        response = self.client.get(path=reverse(
            'api_projects_tasktime_start', kwargs={'task_id': sub_task_id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        slot_id = data['id']

        sleep(60)

        #stop task time
        response = self.client.post(reverse('api_projects_tasktime_stop',
                                            kwargs={'slot_id': slot_id}),
                                    data=json.dumps(
                                        {'details': '<p>test details</p>'}),
                                    content_type=self.content_type,
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        #delete task time
        response = self.client.delete(
            reverse('api_projects_tasktimes',
                    kwargs={'object_ptr': tasktime_id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 204)

        #delete task
        response = self.client.delete(
            reverse('api_projects_tasks', kwargs={'object_ptr': task_id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 204)

        # check subtask
        response = self.client.get(path=reverse(
            'api_projects_tasks', kwargs={'object_ptr': sub_task_id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 404)

        #delete milestone
        response = self.client.delete(
            reverse('api_projects_milestones',
                    kwargs={'object_ptr': milestone_id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 204)

        #delete status
        response = self.client.delete(
            reverse('api_projects_status', kwargs={'object_ptr': sstatus}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 204)

        #delete project
        response = self.client.delete(
            reverse('api_projects', kwargs={'object_ptr': project_id}),
            **self.authentication_headers)
        self.assertEquals(response.status_code, 204)
Exemple #58
0
class TestsFolowsImagesOthers(TestCase):
    def setUp(self):

        self.client = Client()
        self.client_author = Client()
        self.client_anonim = Client()

        self.login_user_name = 'login_user'
        self.login_user = User.objects.create_user(self.login_user_name,
                                                   '*****@*****.**',
                                                   'test_user_2020')
        self.client.force_login(self.login_user)

        self.login_author_name = 'author_user'
        self.login_author = User.objects.create_user(self.login_author_name,
                                                     '*****@*****.**',
                                                     'test_user_2020')
        self.client_author.force_login(self.login_author)

    def test_get_404_page(self):
        """Проверка работы страниц ошибок"""
        response = self.client.get('/strange_page_which_never_will_be_used/')
        self.assertEqual(response.status_code,
                         404,
                         msg='Сервер не возвращает код 404')

    def test_images(self):
        """Проверка загрузки и наличия изображений"""

        img_file = Image.new('RGB', (250, 250), (255, 255, 255))
        img_file.save('tmp.png')

        Group.objects.create(title='group1', slug='g')
        group = Group.objects.get(pk=1)

        with open('tmp.png', 'rb') as img:
            self.client.post(
                reverse('new_post'), {
                    'author': self.login_user,
                    'group': group.id,
                    'text': 'post with image',
                    'image': img
                })
            cache.clear()
            response = self.client.get(reverse('index'))
            self.assertContains(response, '<img')

            response = self.client.get(
                reverse('post', args=[self.login_user_name, 1]))
            self.assertContains(response, '<img')

            response = self.client.get(
                reverse('profile', args=[self.login_user_name]))
            self.assertContains(response, '<img')

            response = self.client.get(reverse('group', args=['g']))
            self.assertContains(response, '<img')

        os.remove('tmp.png')

    def test_bad_images(self):
        """Проверка загрузки не изображения"""

        cache.clear()
        fd, temp_file = tempfile.mkstemp(suffix='.txt', prefix='temp_file_')

        with open(temp_file, 'w') as f:
            f.write('post image')

        with open(temp_file, 'rb') as img:
            post = self.client.post(reverse('new_post'), {
                'author': self.login_user,
                'text': 'post with image',
                'image': img
            },
                                    follow=True)
        os.close(fd)
        os.remove(temp_file)
        self.assertContains(post, 'Загрузите правильное изображение')

    def test_cache(self):
        self.client.post(reverse('new_post'), {
            'author': self.login_user,
            'text': 'I cant see this note!'
        },
                         follow=True)
        cache.clear()

        # первый запрос
        dt0 = datetime.now()
        self.client.get(reverse('index'))
        dt1 = datetime.now()
        timedelta1 = dt1 - dt0

        # Второй запрос
        dt0 = datetime.now()
        self.client.get(reverse('index'))
        dt1 = datetime.now()
        timedelta2 = dt1 - dt0

        self.assertTrue(timedelta2 < timedelta1)

        cache.clear()
        self.client.get(reverse('index'))
        with self.assertNumQueries(0):
            self.client.get(reverse('index'))

    def test_user_can_follow_the_author(self):
        self.client_author.post(reverse('new_post'), {
            'text': 'i am author',
            'author': self.login_author_name
        })

        self.client.post(
            reverse('profile_follow', args=[self.login_author_name]))

        follows = Follow.objects.filter(user=self.login_user,
                                        author=self.login_author).all()

        self.assertEqual(1, follows.count(), msg='No follow created!')

    def test_user_can_unfollow_the_author(self):
        Follow.objects.create(user=self.login_user, author=self.login_author)
        self.client.post(
            reverse('profile_unfollow', args=[self.login_author_name]))

        follows = Follow.objects.filter(user=self.login_user,
                                        author=self.login_author).all()
        self.assertEqual(0, follows.count(), msg='User has not unfolow')

    def test_new_post_appeared_on_follow(self):
        self.client.post(
            reverse('profile_follow', args=[self.login_author_name]))

        self.client_author.post(reverse('new_post'), {
            'text': 'i am author',
            'author': self.login_author_name
        })

        response = self.client.get(reverse('follow_index'))
        self.assertEqual(1,
                         len(response.context['page'].object_list),
                         msg='Post is not appear to follow user')

    def test_new_post_not_appeared_on_unfollow(self):
        self.client_author.post(reverse('new_post'), {
            'text': 'i am author',
            'author': self.login_author_name
        })

        response = self.client.get(reverse('follow_index'))
        self.assertEqual(0,
                         len(response.context['page'].object_list),
                         msg='Post is appear to unfollow user')

    def test_auth_user_can_comment(self):
        self.client_author.post(reverse('new_post'), {
            'text': 'i am author',
            'author': self.login_author_name
        })

        self.client_author.post(
            reverse('add_comment', args=[self.login_author_name, 1]),
            {'text': 'my comment'})
        self.assertEqual(1,
                         len(Comment.objects.all()),
                         msg='auth. user cant comment')
Exemple #59
0
class FeedTest(TestCase):
    fixtures = ['rss_feeds.json']
    
    def setUp(self):
        self.client = Client()

    def test_load_feeds__gawker(self):
        self.client.login(username='******', password='******')
        
        management.call_command('loaddata', 'gawker1.json', verbosity=0)
        
        feed = Feed.objects.get(feed_link__contains='gawker')
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 0)
        
        feed.update(force=True)
        
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 38)
        
        management.call_command('loaddata', 'gawker2.json', verbosity=0)
        
        feed.update(force=True)
        
        # Test: 1 changed char in content
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 38)
        
        url = reverse('load-single-feed', kwargs=dict(feed_id=1))
        response = self.client.get(url)
        feed = json.decode(response.content)
        self.assertEquals(len(feed['stories']), 12)
        
    def test_load_feeds__gothamist(self):
        self.client.login(username='******', password='******')
        
        management.call_command('loaddata', 'gothamist_aug_2009_1.json', verbosity=0)
        feed = Feed.objects.get(feed_link__contains='gothamist')
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 0)
        
        management.call_command('refresh_feed', force=1, feed=4, single_threaded=True, daemonize=False)
        
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 42)
        
        url = reverse('load-single-feed', kwargs=dict(feed_id=4))
        response = self.client.get(url)
        content = json.decode(response.content)
        self.assertEquals(len(content['stories']), 12)
        
        management.call_command('loaddata', 'gothamist_aug_2009_2.json', verbosity=0)
        management.call_command('refresh_feed', force=1, feed=4, single_threaded=True, daemonize=False)
        
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 42)
        
        url = reverse('load-single-feed', kwargs=dict(feed_id=4))
        response = self.client.get(url)
        # print [c['story_title'] for c in json.decode(response.content)]
        content = json.decode(response.content)
        # Test: 1 changed char in title
        self.assertEquals(len(content['stories']), 12)
        
    def test_load_feeds__slashdot(self):
        self.client.login(username='******', password='******')
        
        old_story_guid = "{'original-id': u'http://yro.slashdot.org/story/09/09/05/0112254/Court-Allows-Microsoft-To-Sell-Word-During-Appeal?from=rss', 'gr:original-id': u'http://yro.slashdot.org/story/09/09/05/0112254/Court-Allows-Microsoft-To-Sell-Word-During-Appeal?from=rss'}"
        new_story_guid = "{'original-id': u'http://yro.slashdot.org/story/09/09/05/0112254/Court-Allows-Microsoft-To-Sell-Word-During-Appeal?from=rss!!', 'gr:original-id': u'http://yro.slashdot.org/story/09/09/05/0112254/Court-Allows-Microsoft-To-Sell-Word-During-Appeal?from=rss!!'}"
        
        management.call_command('loaddata', 'slashdot1.json', verbosity=0)
        
        feed = Feed.objects.get(feed_link__contains='slashdot')
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 0)
        
        management.call_command('refresh_feed', force=1, feed=5, single_threaded=True, daemonize=False)
        
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 38)
        
        response = self.client.get(reverse('load-feeds'))
        content = json.decode(response.content)
        self.assertEquals(content['feeds']['5']['nt'], 38)
        
        self.client.post(reverse('mark-story-as-read'), {'story_id': old_story_guid, 'feed_id': 5})
        
        response = self.client.get(reverse('refresh-feeds'))
        content = json.decode(response.content)
        self.assertEquals(content['feeds']['5']['nt'], 37)
        
        management.call_command('loaddata', 'slashdot2.json', verbosity=0)
        management.call_command('refresh_feed', force=1, feed=5, single_threaded=True, daemonize=False)
        
        stories = MStory.objects(story_feed_id=feed.pk)
        self.assertEquals(stories.count(), 38)
        
        url = reverse('load-single-feed', kwargs=dict(feed_id=5))
        response = self.client.get(url)
        
        # pprint([c['story_title'] for c in json.decode(response.content)])
        feed = json.decode(response.content)
        
        # Test: 1 changed char in title
        self.assertEquals(len(feed['stories']), 12)
        
        response = self.client.get(reverse('refresh-feeds'))
        content = json.decode(response.content)
        self.assertEquals(content['feeds']['5']['nt'], 37)
        
    def test_load_feeds__brokelyn__invalid_xml(self):
        self.client.login(username='******', password='******')
        
        management.call_command('loaddata', 'brokelyn.json', verbosity=0)
        management.call_command('refresh_feed', force=1, feed=6, single_threaded=True, daemonize=False)
        
        url = reverse('load-single-feed', kwargs=dict(feed_id=6))
        response = self.client.get(url)
        
        # pprint([c['story_title'] for c in json.decode(response.content)])
        feed = json.decode(response.content)
        
        # Test: 1 changed char in title
        self.assertEquals(len(feed['stories']), 10)
        
    def test_all_feeds(self):
        pass
def test_login_correct(app: Client, user: dict):
    response = app.post('/expenses-manager/login/', user, follow=True)
    assert response.status_code == 200
    assert response.context['user'].username == user['username']