class AdminTests(TestCase):
    fixtures = ['micropages_test.json']

    def setUp(self):        
        self.factory = RequestFactory()    
        self.site = AdminSite()
        self.page = micropages.templates.Loader().find_page('/admin-page/')

    def test_should_return_not_supportsed_on_non_post_preview(self):
        request = self.factory.get('/admin/micropages/page/preview/')
        response = micropages.admin.PageAdmin(self.page, self.site).preview(request)
        self.assertEqual(response.status_code, 405)

    def test_should_return_500_if_previews_page_missing(self):
        request = self.factory.post('/admin/micropages/page/preview/')
        response = micropages.admin.PageAdmin(self.page, self.site).preview(request)
        self.assertEqual(response.status_code, 500)

    def test_should_return_200_page_preview(self):
        request = self.factory.post('/admin/micropages/page/preview/', {'page': 'admin'})
        response = micropages.admin.PageAdmin(self.page, self.site).preview(request)
        self.assertEqual(response.status_code, 200)

    def test_should_process_template_on_page_preview(self):
        request = self.factory.post('/admin/micropages/page/preview/', {'page': 'admin'})
        response = micropages.admin.PageAdmin(self.page, self.site).preview(request)
        self.assertEqual(response.content, 'admin')
Beispiel #2
0
class CoreFormTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create_user(
            username='john', email='lennon@thebeatles.com', password='johnpassword')
        self.factory = RequestFactory()

    def test_valid_form(self):
        request = self.factory.post(
            '', {'username': 'john', 'password': 'johnpassword'})
        form = LoginForm(request.POST)
        self.assertTrue(form.is_valid())

    def test_invalid_form(self):
        request = self.factory.post(
            '', {'username': 'john', 'password': ''})
        form = LoginForm(request.POST)
        self.assertFalse(form.is_valid())

    def test_form_login(self):
        request = self.factory.post('', {'username': 'john', 'password': 'johnpassword'})
        form = LoginForm(request.POST)
        self.assertTrue(form.is_valid())
        user = form.login(request)
        self.assertTrue(user, self.user)
class TestGetAudience(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    @patch_settings(SITE_URL='http://example.com')
    def test_improperly_configured(self):
        # Raise ImproperlyConfigured if SITE_URL doesn't match the request's
        # URL.
        request = self.factory.post('/', SERVER_NAME='www.blah.com')
        with self.assertRaises(ImproperlyConfigured):
            get_audience(request)

    @patch_settings(SITE_URL='http://example.com')
    def test_properly_configured(self):
        # Return SITE_URL if it matches the request URL and DEBUG = True.
        request = self.factory.post('/', SERVER_NAME='example.com')
        self.assertEqual('http://example.com', get_audience(request))

    @patch_settings(SITE_URL=['http://example1.com', 'http://example2.com'])
    def test_iterable(self):
        # Return correct url from iterable SITE_URL, if it contains request URL.
        request = self.factory.post('/', SERVER_NAME='example2.com')
        self.assertEqual('http://example2.com', get_audience(request))

    @patch_settings(DEBUG=True)
    def test_no_site_url(self):
        # If SITE_URL isn't set, use the domain from the request.
        request = self.factory.post('/', SERVER_NAME='www.blah.com')
        self.assertEqual('http://www.blah.com', get_audience(request))
Beispiel #4
0
class ClientViews(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_home(self):
        url = reverse('home')
        request = self.factory.get(url)
        response = home(request)

        self.assertEqual(200, response.status_code)
        self.assertIn("Tic Tac Toe by Jack Slingerland", response.content)

    def test_make_move_with_invalid_parameters(self):
        url = reverse('make-move')
        request = self.factory.post(url)
        response = make_move(request)

        self.assertEqual(200, response.status_code)
        self.assertEqual({
            'error' : 'You are missing a required parameter.'
        }, json.loads(response.content))

    def test_make_move_with_valid_parameters(self):

        game = Game(name='Test Game')
        game.save()

        url = reverse('make-move')
        request = self.factory.post(url, {
            'board' : ',O,X,,X,,,,',
            'game' : game.id,
            'x' : 2,
            'y' : 1
        })
        response = make_move(request)

        self.assertEqual(200, response.status_code)
        self.assertNotIn('error', response.content)
        self.assertEqual(None, json.loads(response.content)['state'])
        self.assertNotEqual(None, json.loads(response.content)['coordinates'])

    def test_new_game_with_invalid_parameters(self):
        url = reverse('new-game')
        request = self.factory.post(url)
        response = new_game(request)

        self.assertEqual(200, response.status_code)
        self.assertEqual({
            'error' : "'name' field is required."
        }, json.loads(response.content))

    def test_new_game_with_valid_parameters(self):
        url = reverse('new-game')
        request = self.factory.post(url, { 'name' : 'Jack' })
        response = new_game(request)

        self.assertEqual(200, response.status_code)
        self.assertNotIn('error', response.content)
        self.assertEqual(Game.objects.get(name='Jack').id, json.loads(response.content)['id'])
class RedeliverAdminActionTest(TestCase):
    def setUp(self):
        self.site = factories.make_world()
        self.admin_site = AdminSite()
        self.admin = DeferredMessageAdmin(DeferredMessage,
            self.admin_site)
        self.factory = RequestFactory()
        self.user = User.objects.get(username='sw')
        self.user.is_superuser = True

    def test_redeliver(self):
        foireq = FoiRequest.objects.all()[0]
        dm = factories.DeferredMessageFactory()
        dm.save()
        req = self.factory.post('/', {})
        req.user = self.user

        result = self.admin.redeliver(req,
                DeferredMessage.objects.filter(
                    id__in=[dm.id]))
        self.assertEqual(result.status_code, 200)

        req = self.factory.post('/', {
            'req_id': foireq.id
        })
        req.user = self.user
        req._messages = default_storage(req)

        result = self.admin.redeliver(req,
                DeferredMessage.objects.filter(
                    id__in=[dm.id]))
        self.assertIsNone(result)

        dm = DeferredMessage.objects.get(id=dm.id)
        self.assertEqual(dm.request, foireq)
Beispiel #6
0
class TestAuthentication(unittest.TestCase):
    def setUp(self):
        self.req_factory = RequestFactory()

    @override_settings(API_KEY='test')
    def test_valid_auth(self):
        http_auth = 'Basic {0}'.format(
            base64.encodestring(settings.API_KEY))
        request = self.req_factory.post('/api/v1/metric/', {},
                                        HTTP_AUTHORIZATION=http_auth)
        auth = SettingsAuthentication()
        auth_resp = auth.authenticate(request)
        self.assertFalse(auth_resp is None, "Authentication failed")

    @override_settings(API_KEY='test')
    def test_invalid_auth(self):
        http_auth = 'Basic {0}'.format(
            base64.encodestring('wrongkey'))
        request = self.req_factory.post('/api/v1/metric/', {},
                               HTTP_AUTHORIZATION=http_auth)
        auth = SettingsAuthentication()
        self.assertRaises(exceptions.AuthenticationFailed, auth.authenticate,
                          request)

    @override_settings(API_KEY='test')
    def test_no_auth(self):
        request = self.req_factory.post('/api/v1/metric/', {})
        auth = SettingsAuthentication()
        auth_resp = auth.authenticate(request)
        self.assertTrue(auth_resp is None, "Authentication succeeded")
Beispiel #7
0
class GetNextTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_no_param(self):
        """If next isn't in the POST params, return None."""
        request = self.factory.post('/')
        eq_(views._get_next(request), None)

    def test_is_safe(self):
        """Return the value of next if it is considered safe."""
        request = self.factory.post('/', {'next': '/asdf'})
        request.get_host = lambda: 'myhost'

        with patch.object(views, 'is_safe_url', return_value=True) as is_safe_url:
            eq_(views._get_next(request), '/asdf')
            is_safe_url.assert_called_with('/asdf', host='myhost')

    def test_isnt_safe(self):
        """If next isn't safe, return None."""
        request = self.factory.post('/', {'next': '/asdf'})
        request.get_host = lambda: 'myhost'

        with patch.object(views, 'is_safe_url', return_value=False) as is_safe_url:
            eq_(views._get_next(request), None)
            is_safe_url.assert_called_with('/asdf', host='myhost')
Beispiel #8
0
class ViewTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = get_user()

    def test_valid_new_vendor_redirects(self):
        request = self.factory.post('/vendors/add',
                                    { 'name': 'test123',
                                      'address': '123 Main st'})
        request.user = self.user

        response = views.new_vendor(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(models.Vendor.objects.filter(name="test123").count(), 1)

    def test_invalid_new_vendor_does_not_save(self):
        request = self.factory.post('/vendors/add',
                                    { 'name': 'test123' })
        request.user = self.user

        response = views.new_vendor(request)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(models.Vendor.objects.filter(name="test123").count(), 0)
Beispiel #9
0
class AdminActionTest(TestCase):
    def setUp(self):
        self.site = factories.make_world()
        self.admin_site = AdminSite()
        self.user_admin = UserAdmin(User, self.admin_site)
        self.factory = RequestFactory()
        self.user = User.objects.get(username='sw')
        self.user.is_superuser = True

    def test_send_mail(self):
        users = User.objects.all()

        req = self.factory.post('/', {})
        req.user = self.user
        result = self.user_admin.send_mail(req, users)
        self.assertEqual(result.status_code, 200)

        req = self.factory.post('/', {
            'subject': 'Test',
            'body': '^{name}|{first_name}|{last_name}|'
        })
        req.user = self.user
        req._messages = default_storage(req)
        mail.outbox = []

        result = self.user_admin.send_mail(req, users)
        self.assertIsNone(result)
        self.assertEqual(len(mail.outbox), users.count())
        message = mail.outbox[0]
        user = users[0]
        self.assertIn('|%s|' % user.first_name, message.body)
        self.assertIn('|%s|' % user.last_name, message.body)
        self.assertIn('^%s|' % user.get_full_name(), message.body)
Beispiel #10
0
class ProjectImageFormTestCase(ProjectBaseTestCase):

    def setUp(self):
        self.request_factory = RequestFactory()
        self.project = self.create_project()

    def test_valid_file_upload(self):
        filename = self.get_random_string()
        f = self.create_file(filename=filename)
        request = self.request_factory.post('/', {'file': f})
        request.is_ajax = True
        form = ProjectImageForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
            self.assertEqual(instance.get_filename(), filename)
        else:
            self.fail('Form should be valid')

    def test_invalid_upload(self):
        request = self.request_factory.post('/', {'filez': self.create_file()})
        request.is_ajax = True
        form = ProjectImageForm(request.POST or None, request.FILES or None)
        self.assertFalse(form.is_valid())

    def test_no_file(self):
        request = self.request_factory.post('/', {})
        request.is_ajax = True
        form = ProjectImageForm(request.POST or None, request.FILES or None)
        self.assertFalse(form.is_valid())
Beispiel #11
0
class SubscribeEmailValidationTest(TestCase):
    email = 'dude@example.com'
    data = {
        'email': email,
        'newsletters': 'os',
    }
    view = 'subscribe'

    def setUp(self):
        self.rf = RequestFactory()

    @patch('news.views.validate_email')
    def test_invalid_email(self, mock_validate):
        """Should return proper error for invalid email."""
        mock_validate.side_effect = views.EmailValidationError('Invalid email')
        view = getattr(views, self.view)
        resp = view(self.rf.post('/', self.data))
        resp_data = json.loads(resp.content)
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(resp_data['status'], 'error')
        self.assertEqual(resp_data['code'], errors.BASKET_INVALID_EMAIL)
        self.assertNotIn('suggestion', resp_data)

    @patch('news.views.validate_email')
    def test_invalid_email_suggestion(self, mock_validate):
        """Should return proper error for invalid email."""
        mock_validate.side_effect = views.EmailValidationError('Invalid email',
                                                               'walter@example.com')
        view = getattr(views, self.view)
        resp = view(self.rf.post('/', self.data))
        resp_data = json.loads(resp.content)
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(resp_data['status'], 'error')
        self.assertEqual(resp_data['code'], errors.BASKET_INVALID_EMAIL)
        self.assertEqual(resp_data['suggestion'], 'walter@example.com')
Beispiel #12
0
class SignupViewTestCase(unittest.TestCase):
    
    def setUp(self):
        self.factory = RequestFactory()
    
    def test_get(self):
        request = self.factory.get(reverse("account_signup"))
        request.user = AnonymousUser()
        response = SignupEnabledView.as_view()(request)
        self.assertEqual(response.status_code, 200)
    
    def test_get_disabled(self):
        request = self.factory.get(reverse("account_signup"))
        request.user = AnonymousUser()
        response = SignupDisabledView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.template_name, "account/signup_closed.html")
    
    def test_post_disabled(self):
        request = self.factory.post(reverse("account_signup"))
        request.user = AnonymousUser()
        response = SignupDisabledView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.template_name, "account/signup_closed.html")
    
    def test_post_successful(self):
        post = {"username": "user", "password": "pwd",
            "password_confirm": "pwd", "email": "info@example.com"}
        request = self.factory.post(reverse("account_signup"), post)
        request.user = AnonymousUser()
        response = SignupEnabledView.as_view()(request)
        self.assertEqual(response.status_code, 302)
        user = User.objects.get(username="user")
        self.asserEqual(user.email, "info@example.com")
Beispiel #13
0
class MemberTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.member = models.Member.objects.create(email="me@example.com")

    def test_signing(self):
        member_via_key = models.Member.objects.get_by_unsubscribe_key(
                                                    self.member.unsubscribe_key)
        self.assertEqual(self.member.pk, member_via_key.pk)

    def test_signup(self):
        email = 'me2@example.com'
        request = self.factory.post(reverse('launchpad_signup'),
                                    {'email': email})
        response = views.Signup.as_view()(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], reverse('launchpad_success'))
        member = models.Member.objects.get(email=email)

    def test_good_unsubscribe(self):
        key = self.member.unsubscribe_key
        request = self.factory.post(reverse('launchpad_unsubscribe',
                                            args=(key,)))
        response = views.Unsubscribe.as_view()(request, key=key)
        self.assertEqual(response.status_code, 200)
        member = models.Member.objects.get(pk=self.member.pk)
        self.assertFalse(member.is_subscribed)

    def test_bad_unsubscribe(self):
        bad_key = "notavalidkey9876543210"
        request = self.factory.post(reverse('launchpad_unsubscribe',
                                            args=(bad_key,)))
        self.assertRaises(http.Http404, views.Unsubscribe.as_view(), request, key=bad_key)
Beispiel #14
0
class TeamViewTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get('/')
        self.response = Team().get(self.request)
        self.request_post = self.factory.post('/team/', {'name': 'test-team'})
        self.request_post.session = {}
        self.response_mock = Mock()

    def test_should_require_login_to_create_team(self):
        assert issubclass(Team, LoginRequiredView)

    def test_team_should_render_expected_template(self):
        self.assertEqual('auth/team.html', self.response.template_name)

    def test_context_should_contain_form(self):
        self.assertIn('form', self.response.context_data.keys())

    def test_form_in_context_should_has_a_instance_of_TeamForm(self):
        form = self.response.context_data.get('form')
        self.assertTrue(isinstance(form, TeamForm))

    def test_get_request_team_url_should_return_200(self):
        try:
            self.client.get('/team/')
        except Http404:
            assert False

    def test_post_with_name_should_send_request_post_to_tsuru_with_args_expected(self):
        self.request_post.session = {'tsuru_token': 'tokentest'}
        with patch('requests.post') as post:
            Team().post(self.request_post)
            self.assertEqual(1, post.call_count)
            post.assert_called_with('%s/teams' % settings.TSURU_HOST,
                                    data='{"name": "test-team"}',
                                    headers={'authorization': self.request_post.session['tsuru_token']})

    def test_post_with_valid_name_should_return_context_with_message_expected(self):
        with patch('requests.post') as post:
            self.response_mock.status_code = 200
            post.side_effect = Mock(return_value=self.response_mock)
            response = Team().post(self.request_post)
            self.assertEqual("Team was successfully created", response.context_data.get('message'))

    def test_post_with_invalid_name_should_return_500(self):
        with patch('requests.post') as post:
            self.response_mock.status_code = 500
            self.response_mock.content = 'Error'
            post.side_effect = Mock(return_value=self.response_mock)
            response = Team().post(self.request_post)
            self.assertEqual('Error', response.context_data.get('errors'))

    def test_post_without_name_should_return_form_with_errors(self):
        request = self.factory.post('/team/', {'name': ''})
        request.session = {}
        response = Team().post(request)
        form =  response.context_data.get('form')
        self.assertIn('name', form.errors)
        self.assertIn(u'This field is required.', form.errors.get('name'))
Beispiel #15
0
    def test_valid_key(self):
        """Make sure the key is valid"""
        actual_ip_plus_desc = actual_ip_plus_context(
            lambda req: req.POST.get('description', 'no description')
        )

        url = reverse('feedback')
        factory = RequestFactory(HTTP_X_CLUSTER_CLIENT_IP='192.168.100.101')

        # create a request with this as the description
        desc = u'\u5347\u7ea7\u4e86\u65b0\u7248\u672c\u4e4b\u540e' * 16
        req = factory.post(url, {
            'description': desc
        })
        key = actual_ip_plus_desc(req)

        # Key can't exceed memcached 250 character max
        length = len(key)
        assert length < 250

        # Key must be a string
        assert isinstance(key, str)

        # create a request with this as the description
        second_desc = u'\u62e9\u201c\u5728\u65b0\u6807\u7b7e\u9875\u4e2d' * 16
        second_req = factory.post(url, {
            'description': second_desc
        })
        second_key = actual_ip_plus_desc(second_req)

        # Two descriptions with the same ip address should produce
        # different keys.
        assert key != second_key
class TestConfirmToken(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.uuid = 'f3a12ae7-4f05-4fce-8135-bc51a9522116'
        self.undashified_uuid = 'f3a12ae74f054fce8135bc51a9522116'
        self.username = 'confirming-user'
        self.ureporter = Ureporter(uuid=self.uuid, user=User.objects.create_user(self.username))
        self.ureporter.token = 1234
        self.ureporter.save()

    @patch('requests.delete')
    def tearDown(self, mock_requests_delete):
        mock_requests_delete.side_effect = None
        self.ureporter.delete()

    def test_confirm_token_with_good_code(self):
        request = self.factory.post('/confirm-token', {'phone': self.username, 'text': '1234'})
        response = confirm_token(request)
        self.assertEqual(json.loads(response.content)['token_ok'], 'true')

    def test_confirm_token_with_bad_code(self):
        request = self.factory.post('/confirm-token', {'phone': self.username, 'text': '8888'})
        response = confirm_token(request)
        self.assertEqual(json.loads(response.content)['token_ok'], 'false')
Beispiel #17
0
class MenuAdminTest(TestCase):
    fixtures = ['simple_menus', 'simple_site']
    
    def setUp(self):
        self.factory = RequestFactory()

    def test_delete_item(self):
        request = self.factory.post('/admin/navigation/menu/1/delete_item', {'id': 11})
        
        admin = MenuAdmin(Menu, None)
        response = admin.delete_item_view(request, 1)
        self.assertNotEqual(None, response)
        
    def test_update_item(self):
        request = self.factory.post('/admin/navigation/menu/1/update_item', {'id': 11, 'title': 'new title', 'parent' : ''})
        
        admin = MenuAdmin(Menu, None)
        response = admin.update_item_view(request, 1)
        self.assertNotEqual(None, response)
        
    def test_refresh_items(self):
        from navigation.admin import refresh_items
        queryset = Menu.objects.filter(id=1)
        refresh_items(None, None, queryset)
        
    def test_add_item_performance(self):
        request = self.factory.post('/admin/navigation/menu/1/add_item', {})
        
        admin = MenuAdmin(Menu, None)
        for i in range(30):
            admin.add_item_view(request, 1)
Beispiel #18
0
class SignupViewTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get('/')
        self.response = Signup().get(self.request)
        self.response_mock = Mock()

    def test_signup_should_show_template(self):
        self.assertEqual('auth/signup.html', self.response.template_name)

    def test_context_should_contain_form(self):
        form = self.response.context_data['signup_form']
        self.assertIsInstance(form, SignupForm)

    def test_should_validate_data_from_post(self):
        data = {'email': '', 'password': '', 'same_password_again': ''}
        request = self.factory.post('/signup', data)
        response = Signup().post(request)
        form = response.context_data['signup_form']

        self.assertIn(u'This field is required.', form.errors['email'])
        self.assertIn(u'This field is required.', form.errors['password'])
        self.assertIn(u'This field is required.', form.errors['same_password_again'])

    def test_post_with_data_should_send_request_post_to_tsuru_with_args_expected(self):
        data = {'email': 'test@test.com', 'password': 'abc123', 'same_password_again': 'abc123'}
        request = self.factory.post('/signup', data)
        with patch('requests.post') as post:
            Signup().post(request)
            self.assertEqual(1, post.call_count)
            post.assert_called_with('%s/users' % settings.TSURU_HOST, data='{"password": "abc123", "email": "test@test.com"}')
Beispiel #19
0
class LogoutTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

        _get_next_patch = patch('django_browserid.views._get_next')
        self._get_next = _get_next_patch.start()
        self.addCleanup(_get_next_patch.stop)

    def test_redirect(self):
        """Include LOGOUT_REDIRECT_URL in the response."""
        request = self.factory.post('/')
        logout = views.Logout.as_view()
        self._get_next.return_value = None

        with patch.object(views.Logout, 'redirect_url', '/test/foo'):
            with patch('django_browserid.views.auth.logout') as auth_logout:
                response = logout(request)

        auth_logout.assert_called_with(request)
        eq_(response.status_code, 200)
        self.assert_json_equals(response.content, {'redirect': '/test/foo'})

    def test_redirect_next(self):
        """
        If _get_next returns a URL, use it for the redirect parameter.
        """
        request = self.factory.post('/')
        logout = views.Logout.as_view()
        self._get_next.return_value = '/test/bar'

        with patch.object(views.Logout, 'redirect_url', '/test/foo'):
            with patch('django_browserid.views.auth.logout'):
                response = logout(request)

        self.assert_json_equals(response.content, {'redirect': '/test/bar'})
Beispiel #20
0
class CRUDViewTest(TestCase):
    names = ['John', 'Anne', 'Chris', 'Beatrice', 'Matt']

    def setUp(self):
        self.factory = RequestFactory()
        for name in self.names:
            DummyModel(name=name).save()

    def test_ng_query(self):
        request = self.factory.get('/crud/')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        for obj in data:
            db_obj = DummyModel.objects.get(pk=obj['pk'])
            self.assertEqual(obj['name'], db_obj.name)

    def test_ng_get(self):
        request = self.factory.get('/crud/?pk=1')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        self.assertEqual(self.names[0], data['name'])

    def test_ng_save_create(self):
        request = self.factory.post('/crud/',
                                    data=json.dumps({'name': 'Leonard'}),
                                    content_type='application/json')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        pk = data['pk']

        request2 = self.factory.get('/crud/?pk=%d' % pk)
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        self.assertEqual(data2['name'], 'Leonard')

    def test_ng_save_update(self):
        request = self.factory.post('/crud/?pk=1',
                                    data=json.dumps({'pk': 1, 'name': 'John2'}),
                                    content_type='application/json')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        self.assertEqual(data['name'], 'John2')

        request2 = self.factory.get('/crud/?pk=1')
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        self.assertEqual(data2['name'], 'John2')

    def test_ng_delete(self):
        request = self.factory.delete('/crud/?pk=1')
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        deleted_name = data['name']

        request2 = self.factory.get('/crud/')
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        for obj in data2:
            self.assertTrue(deleted_name != obj['name'])
Beispiel #21
0
class QuestionFormTestCase(QandaBaseTestCase):

    def setUp(self):
        self.request_factory = RequestFactory()
        self.question = self.create_question()

    def test_edit_invalid(self):
        request = self.request_factory.post('/', {})
        form = QuestionForm(request.POST, instance=self.question)
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['title'], ['This field is required.'])
        self.assertEqual(form.errors['question'], ['This field is required.'])
        self.assertEqual(Action.objects.count(), 0,
            'Invalid form submission should not result in an action'
        )

    def test_create_invalid(self):
        request = self.request_factory.post('/', {})
        site = Site.objects.get(id=current_site_id)
        question = Question(user=self.create_user(), site=site)
        form = QuestionForm(request.POST, instance=question)
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['title'], ['This field is required.'])
        self.assertEqual(form.errors['question'], ['This field is required.'])
        self.assertEqual(Action.objects.count(), 0,
            'Invalid form submission should not result in an action'
        )

    def test_edit_valid(self):
        post_data = {
            'title': self.get_random_string(),
            'question': self.get_random_string(),
        }
        request = self.request_factory.post('/', post_data)
        form = QuestionForm(request.POST, instance=self.question)
        if form.is_valid():
            form.save()
            self.assertEqual(Action.objects.count(), 0,
                'editting a question should not result in an action'
            )
        else:
            self.fail('Form should be valid')

    def test_create_valid(self):
        post_data = {
            'title': self.get_random_string(),
            'question': self.get_random_string(),
        }
        request = self.request_factory.post('/', post_data)
        site = Site.objects.get(id=current_site_id)
        question = Question(user=self.create_user(), site=site)
        form = QuestionForm(request.POST, instance=question)
        if form.is_valid():
            form.save()
            self.assertEqual(Action.objects.count(), 1,
                'Creating a question should result in an action'
            )
        else:
            self.fail('Form should be valid')
class TestSendToken(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.uuid = 'f3a12ae7-4f05-4fce-8135-bc51a9522116'
        self.undashified_uuid = undashify_user(self.uuid)
        self.ureporter = Ureporter.objects.create(uuid=self.uuid, user=User.objects.create_user('username'))
        self.username = self.ureporter.urn_tel
        self.ureporter.user.email = 'an@existing.user'
        self.ureporter.save()

    @patch('requests.delete')
    def tearDown(self, mock_requests_delete):
        mock_requests_delete.side_effect = None
        self.ureporter.delete()

    @patch('webparticipation.apps.send_token.tasks.send_verification_token.delay')
    def test_send_token_does_not_accept_get(self, mock_send_verification_token):
        mock_send_verification_token.return_value = None
        request = self.factory.get('/send-token', {'phone': self.undashified_uuid, 'text': 'any@kinda.address'})
        response = send_token(request)
        self.assertEqual(response, None)

    @patch('webparticipation.apps.send_token.tasks.send_verification_token.delay')
    def test_send_token_to_new_user(self, mock_send_verification_token):
        mock_send_verification_token.return_value = None
        request = self.factory.post('/send-token', {'phone': self.username, 'text': 'an@ok.address'})
        response = send_token(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['send_token'], 'send')

    @patch('requests.delete')
    @patch('webparticipation.apps.send_token.tasks.send_verification_token.delay')
    def test_send_token_to_user_that_has_not_finished_registration(
            self, mock_send_verification_token, mock_requests_delete):
        mock_send_verification_token.return_value = None
        mock_requests_delete.side_effect = None
        request = self.factory.post('/send-token', {'phone': self.username, 'text': 'an@existing.user'})
        response = send_token(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['send_token'], 'send')

    @patch('requests.delete')
    @patch('webparticipation.apps.send_token.tasks.send_verification_token.delay')
    def test_do_not_send_token_to_existing_user(self, mock_send_verification_token, mock_requests_delete):
        mock_send_verification_token.return_value = None
        mock_requests_delete.side_effect = None
        self.ureporter.token = 0
        self.ureporter.save()
        request = self.factory.post('/send-token', {'phone': self.username, 'text': 'an@existing.user'})
        response = send_token(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)['send_token'], 'exists')

    @patch('django.core.mail.EmailMessage.send')
    def test_task_send_verification_message_sent(self, mock_email_send):
        send_verification_token(self.ureporter)
        mock_email_send.assert_called_with()
Beispiel #23
0
class LoginUserTest(MockedCloudTestCase):

    def setUp(self):
        super(LoginUserTest, self).setUp()
        self.factory = RequestFactory()
        # Create an user to check login attempts against
        self.existing_user = User.objects.create_user(username='existinguser', cloud_fqdn='existingserver')

    def tearDown(self):
        self.existing_user.delete()

    def test_login_good_credentials(self):
        good_creds={'username': 'existinguser',
                    'password': 'goodpass',
                    'cloud_fqdn': 'existingserver',}
        request = self.factory.post(reverse(login_user), data=good_creds)
        self.do_session_middleware_stuff(request)
        resp = login_user(request)
        self.assertEqual(resp.status_code, 200)

    def test_login_bad_credentials(self):
        bad_creds={'username': 'existinguser',
                   'password': 'badpass',
                   'cloud_fqdn': 'existingserver',}
        request = self.factory.post(reverse(login_user), data=bad_creds)
        self.do_session_middleware_stuff(request)
        # Set mocked backend to fail authentication
        self.set_auth_result(False)
        resp = login_user(request)
        self.assertEqual(resp.status_code, 401)

    def test_login_missing_credentials(self):
        missing_creds={'username': 'existinguser',
                       'cloud_fqdn': 'existingserver',}
        request = self.factory.post(reverse(login_user), data=missing_creds)
        resp = login_user(request)
        self.assertEqual(resp.status_code, 400)

    def test_login_bad_methods(self):
        get_request = self.factory.get(reverse(login_user))
        resp = login_user(get_request)
        self.assertEqual(resp.status_code, 405)
        put_request = self.factory.put(reverse(login_user))
        resp = login_user(put_request)
        self.assertEqual(resp.status_code, 405)
        delete_request = self.factory.delete(reverse(login_user))
        resp = login_user(delete_request)
        self.assertEqual(resp.status_code, 405)

    def test_login_no_persistent_session(self):
        good_creds={'username': 'existinguser',
            'password': 'goodpass',
            'cloud_fqdn': 'existingserver',
            'persistent_session': 'False'}
        resp = self.client.post(reverse(login_user), good_creds)
        self.assertEqual(resp.status_code, 200)
        session_cookie = self.client.cookies['sessionid']
        self.assertEqual(session_cookie['expires'], "")
Beispiel #24
0
class ViewTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def add_session(self, request):
        SessionMiddleware().process_request(request)

    def test_set_timezone(self):
        from .views import TimezoneView
        from pytz import timezone as tz

        request = self.factory.post("/abc", {"timezone": "America/Denver"})
        self.add_session(request)

        response = TimezoneView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        self.assertIn("detected_timezone", request.session)
        self.assertTrue(tz(request.session["detected_timezone"]))
        temp = tz(request.session["detected_timezone"])
        self.assertIsInstance(temp, BaseTzInfo)

    def test_get_timezone(self):
        from .views import TimezoneView

        request = self.factory.get("/abc")
        self.add_session(request)

        response = TimezoneView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Your Timezone is:")

    def test_no_timezone(self):
        from .views import TimezoneView

        request = self.factory.post("/abc")
        self.add_session(request)

        response = TimezoneView.as_view()(request)
        self.assertEqual(response.status_code, 400)

    def test_none_timezone(self):
        from .views import TimezoneView

        request = self.factory.post("/abc", {"timezone": "None"})
        self.add_session(request)

        response = TimezoneView.as_view()(request)
        self.assertContains(response, "America/Chicago")
        self.assertEqual(response.status_code, 200)

    def test_bad_timezone(self):
        from .views import TimezoneView

        request = self.factory.post("/abc", {"timezone": "12foo34"})
        self.add_session(request)

        response = TimezoneView.as_view()(request)
        self.assertEqual(response.status_code, 400)
Beispiel #25
0
class TeamViewTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get('/')
        self.request.session = {"tsuru_token": "admin"}
        self.response = Add.as_view()(self.request)
        self.request_post = self.factory.post('/team/', {'name': 'test-team'})
        self.request_post.session = {"tsuru_token": "admin"}

    def test_should_require_login_to_create_team(self):
        assert issubclass(Add, LoginRequiredView)

    def test_team_should_render_expected_template(self):
        self.assertEqual('auth/team.html', self.response.template_name)

    def test_context_should_contain_form(self):
        self.assertIn('form', self.response.context_data.keys())

    def test_form_in_context_should_has_a_instance_of_TeamForm(self):
        form = self.response.context_data.get('form')
        self.assertTrue(isinstance(form, TeamForm))

    def test_get_request_team_url_should_not_return_404(self):
        response = self.client.get(reverse('team-add'))
        self.assertNotEqual(404, response.status_code)

    @patch('requests.post')
    def test_post_sends_request_to_tsuru(self, post):
        self.request_post.session = {'tsuru_token': 'tokentest'}
        Add.as_view()(self.request_post)
        self.assertEqual(1, post.call_count)
        post.assert_called_with(
            '%s/teams' % settings.TSURU_HOST,
            data='{"name": "test-team"}',
            headers={'authorization':
                     self.request_post.session['tsuru_token']})

    @patch('requests.post')
    def test_valid_post_redirect_to_team_list(self, post):
        post.return_value = Mock(status_code=200)
        response = Add.as_view()(self.request_post)
        self.assertEqual(302, response.status_code)
        self.assertEqual(reverse('team-list'), response.items()[1][1])

    @patch('requests.post')
    def test_post_with_invalid_name_should_return_500(self, post):
        post.return_value = Mock(status_code=500, content='Error')
        response = Add.as_view()(self.request_post)
        self.assertEqual('Error', response.context_data.get('errors'))

    def test_post_without_name_should_return_form_with_errors(self):
        request = self.factory.post('/team/', {'name': ''})
        request.session = {"tsuru_token": "admin"}
        response = Add.as_view()(request)
        form = response.context_data.get('form')
        self.assertIn('name', form.errors)
        self.assertIn(u'This field is required.', form.errors.get('name'))
Beispiel #26
0
    def test_params(self):
        factory = RequestFactory()
        request = factory.post('/', {'post': 'data'})
        params = self.lti._params(request)
        self.assertTrue('post' in params)

        request = factory.post('/', {'get': 'data'})
        params = self.lti._params(request)
        self.assertTrue('get' in params)
Beispiel #27
0
class TestAdministrarProjectos(TestCase):
    """
    *Test para Administración de usuarios, pruebas realizadas:*
        + *ChangeProject*: Test de vista y modificación de los atributos de un proyecto en el sistema.
        + *CreateProject*: Test de Vista y creación de un nuevo proyecto en el sistema.
    """
    un_admin = 'admin'
    pw_admin = 'admin'

    def setUp(self):
        """
        *Crea el usuario 'admin' con contraseña 'admin' para las pruebas.*
        """
        UsuarioFactory.create()
        self.factory = RequestFactory()

    def test_createProject_response(self):
        """
        *Test para la vista de creacion de proyectos en el sistema*
        """
        print '\nInicio - Prueba: createProject'
        self.user = Usuario.objects.get(username='admin')
        dato = {'nombre': 'Proyecto1', 'lider_proyecto': '2', 'descripcion': 'Test:CreacionProyecto'}
        login = self.client.login(username='admin', password='admin')
        self.assertTrue(login)
        request = self.factory.post('createproject/', dato)
        request.user = self.user
        response = createProject(request)
        self.assertEqual(response.status_code, 302, 'Error al crear el Proyecto')
        print 'Proyecto creado exitosamente'
        print Proyecto.objects.all()
        print 'Fin - Prueba: createProject\n'

    def test_changeProject_response(self):
        """
        *Test para la vista de modificacion de proyectos en el sistema*
        """
        print '\nInicio - Prueba: changeProject'
        self.user = Usuario.objects.get(username='admin')
        dato1 = {'nombre': 'Proyecto', 'lider_proyecto': '1', 'estado': 'PEN', 'descripcion': 'Test:CreadoProyecto'}
        login = self.client.login(username='admin', password='admin')
        self.assertTrue(login)
        form = NewProjectForm(dato1)
        if form.is_valid():
            form.save()
            print 'Proyecto: '+form['nombre'].value()+' creado exitosamente en la Base de Datos'
        else:
            print 'Error en los datos del formulario de creación'
        dato2 = {'nombre': 'ProyectoModificado', 'lider_proyecto': '1', 'estado': 'PEN', 'descripcion': 'Test:ModificadoProyecto'}
        request = self.factory.post('changeproject/', dato2)
        request.user = self.user
        request.session = {}
        response = changeProject(request, '1')
        self.assertEqual(response.status_code, 302, 'Error al modificar el Proyecto')
        print 'Proyecto Modificado Exitosamente'
        print Proyecto.objects.all()
        print 'Fin - Prueba: changeProject'
Beispiel #28
0
class UserRepoSyncTest(TestCase):
    #
    # These are kind of terrible now. They test for a forbidden response is
    # legit, but we're short circuiting the POST to sync as to not make
    # an external request to GitHub.
    #
    fixtures = ['gitspatial/fixtures/test_data.json']

    def setUp(self):
        self.sal = User.objects.get(id=6)
        self.jason = User.objects.get(id=5)
        self.factory = RequestFactory()

    def test_user_can_sync_own_repo(self):
        request = self.factory.post('/user/repo/22/sync?testing=1')
        request.user = self.jason
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 201)

    def test_user_cannot_sync_others_repo(self):
        request = self.factory.post('/user/repo/22/sync')
        request.user = self.sal
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 403)

    def test_user_can_unsync_own_repo(self):
        request = self.factory.delete('/user/repo/22/sync?testing=1')
        request.user = self.jason
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 204)

    def test_user_cannot_unsync_others_repo(self):
        request = self.factory.delete('/user/repo/22/sync')
        request.user = self.sal
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 403)

    def test_invalid_method_put(self):
        request = self.factory.put('/user/repo/22/sync?testing=1')
        request.user = self.jason
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 405)

    def test_invalid_method_get(self):
        request = self.factory.get('/user/repo/22/sync?testing=1')
        request.user = self.jason
        response = user_repo_sync(request, repo_id=22)
        self.assertEqual(response.status_code, 405)

    def test_user_repo_sync_dne(self):
        request = self.factory.post('/user/repo/99999/sync')
        request.user = self.jason
        try:
            response = user_repo_sync(request, repo_id=99999)
        except Exception as exc:
            pass
        self.assertTrue(isinstance(exc, Http404))
Beispiel #29
0
class CRUDViewTest(TestCase):
    names = ["John", "Anne", "Chris", "Beatrice", "Matt"]

    def setUp(self):
        self.factory = RequestFactory()
        for name in self.names:
            DummyModel(name=name).save()

    def test_ng_query(self):
        request = self.factory.get("/crud/")
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        for obj in data:
            db_obj = DummyModel.objects.get(pk=obj["pk"])
            self.assertEqual(obj["name"], db_obj.name)

    def test_ng_get(self):
        request = self.factory.get("/crud/?pk=1")
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        self.assertEqual(self.names[0], data["name"])

    def test_ng_save_create(self):
        request = self.factory.post("/crud/", data=json.dumps({"name": "Leonard"}), content_type="application/json")
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        pk = data["pk"]

        request2 = self.factory.get("/crud/?pk=%d" % pk)
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        self.assertEqual(data2["name"], "Leonard")

    def test_ng_save_update(self):
        request = self.factory.post(
            "/crud/?pk=1", data=json.dumps({"pk": 1, "name": "John2"}), content_type="application/json"
        )
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        self.assertEqual(data["name"], "John2")

        request2 = self.factory.get("/crud/?pk=1")
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        self.assertEqual(data2["name"], "John2")

    def test_ng_delete(self):
        request = self.factory.delete("/crud/?pk=1")
        response = CRUDTestView.as_view()(request)
        data = json.loads(response.content)
        deleted_name = data["name"]

        request2 = self.factory.get("/crud/")
        response2 = CRUDTestView.as_view()(request2)
        data2 = json.loads(response2.content)
        for obj in data2:
            self.assertTrue(deleted_name != obj["name"])
class UtilsGetVotedObjectsTest(TestCase):

    def setUp(self):
        self.request_factory = RequestFactory()
        self.user = UserFactory()
        self.ideas = (
            IdeaFactory(),
            IdeaFactory(),
        )
        idea_content_type = ContentType.objects.get_for_model(Idea)
        self.comments = (
            CustomComment.objects.create(
                content_type=idea_content_type,
                object_pk=self.ideas[0].pk,
                user_name="A Person",
                comment="Comment #1",
                site_id=1
            ),
            CustomComment.objects.create(
                content_type=idea_content_type,
                object_pk=self.ideas[1].pk,
                user_name="Someone",
                comment="Comment #2",
                site_id=1
            ),
        )

    def test_ideas(self):
        request = self.request_factory.post(
            "/fi/ideat/{}/kannata/".format(self.ideas[0].id), **HEADERS
        )
        request.user = AnonymousUser()

        vote_object = vote(request, Idea, self.ideas[0].pk, Vote.VOTE_UP)
        self.assertNotEqual(vote_object, False)

        request.COOKIES[Voter.VOTER_COOKIE] = vote_object.voter.voter_id
        voted_ids = get_voted_objects(request, [self.ideas[0], self.ideas[1]], Idea)

        # Expect only the voted idea 0 to be returned.
        self.assertListEqual(voted_ids, [self.ideas[0].id])

    def test_comments(self):
        request = self.request_factory.post(
            "/fi/kommentit/{}/kannata".format(self.comments[0].pk), **HEADERS
        )
        request.user = AnonymousUser()

        vote_object = vote(request, CustomComment, self.comments[0].pk, Vote.VOTE_UP)
        self.assertNotEqual(vote_object, False)

        request.COOKIES[Voter.VOTER_COOKIE] = vote_object.voter.voter_id
        voted_ids = get_voted_objects(request, self.comments, CustomComment)

        # Expect only the voted comment 0 to be returned.
        self.assertListEqual(voted_ids, [self.comments[0].pk])