Example #1
0
    def test_gets_200_on_existing_page(self):
        post = self.create_post()
        c = Client()
        results = c.get(post.get_absolute_url())

        self.assertEqual(results.status_code, 200)
        self.assertTrue(isinstance(results.context["post"], Post))
Example #2
0
    def test_broken_500_handler_with_middleware(self):
        with Settings(BREAK_THAT_500=True, INSTALLED_APPS=["raven.contrib.django"]):
            client = TestClient(REMOTE_ADDR="127.0.0.1")
            client.handler = MockSentryMiddleware(MockClientHandler())

            self.assertRaises(Exception, client.get, reverse("sentry-raise-exc"))

            assert len(self.raven.events) == 2
            event = self.raven.events.pop(0)

            self.assertTrue("sentry.interfaces.Exception" in event)
            exc = event["sentry.interfaces.Exception"]
            self.assertEquals(exc["type"], "Exception")
            self.assertEquals(exc["value"], "view exception")
            self.assertEquals(event["level"], logging.ERROR)
            self.assertEquals(event["message"], "Exception: view exception")
            self.assertEquals(event["culprit"], "tests.contrib.django.views in raise_exc")

            event = self.raven.events.pop(0)

            self.assertTrue("sentry.interfaces.Exception" in event)
            exc = event["sentry.interfaces.Exception"]
            self.assertEquals(exc["type"], "ValueError")
            self.assertEquals(exc["value"], "handler500")
            self.assertEquals(event["level"], logging.ERROR)
            self.assertEquals(event["message"], "ValueError: handler500")
            self.assertEquals(event["culprit"], "tests.contrib.django.urls in handler500")
Example #3
0
class AdminTest(TestCase):
    fixtures = ["l10n-data.yaml", "sample-store-data.yaml", "products.yaml", "initial_data.yaml"]

    def setUp(self):
        self.client = Client()
        user = User.objects.create_user("fredsu", "fred@root.org", "passwd")
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username="fredsu", password="passwd")

    def tearDown(self):
        cache_delete()

    def test_index(self):
        response = self.client.get("/admin/")
        self.assertContains(response, "contact/contact/", status_code=200)

        # def test_product(self):
        response = self.client.get("/admin/product/product/1/")
        self.assertContains(response, "Django Rocks shirt", status_code=200)

        # def test_configurableproduct(self):
        response = self.client.get("/admin/configurable/configurableproduct/1/")
        self.assertContains(response, "Small, Black", status_code=200)
Example #4
0
class FeedTest(TestCase):
    fixtures = ["00_initial_data.json"]

    def setUp(self):
        self.client = Client()
        seconds = datetime.datetime.now().microsecond
        self.user = User(username="djtracker_feed%s" % seconds, email="djtracker@djtracker_feed.com")
        self.user.set_password("password")
        self.user.save()

    def test_personal_feed(self):
        response = self.client.get("/feeds/personal/%s/%s/" % (self.user.id, self.user.userprofile.uuid))

        self.assertEqual(response.status_code, 200)

    def test_project_feed(self):
        response = self.client.get("/feeds/project/1/")

        self.assertEqual(response.status_code, 200)

    def test_failed_personal_feed(self):
        response = self.client.get("/feeds/personal/%s/%s/" % (self.user.id, self.user.userprofile.uuid[0:-2]))

        self.assertEqual(response.status_code, 404)

    def test_failed_project_feed(self):
        response = self.client.get("/feeds/project/123414/")

        self.assertEqual(response.status_code, 404)
Example #5
0
 def handle(self, *args, **options):
     """Request pages and build output."""
     settings.DEBUG = False
     if args:
         pages = args
         available = list(get_pages())
         invalid = []
         for page in pages:
             if page not in available:
                 invalid.append(page)
         if invalid:
             msg = "Invalid pages: {}".format(", ".join(invalid))
             raise CommandError(msg)
     else:
         pages = get_pages()
         if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
             shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
         os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
         os.makedirs(settings.STATIC_ROOT)
     call_command("collectstatic", interactive=False, clear=True, verbosity=0)
     call_command("compress", interactive=False, force=True)
     client = Client()
     for page in get_pages():
         url = reverse("page", kwargs={"slug": page})
         response = client.get(url)
         if page == "index":
             output_dir = settings.SITE_OUTPUT_DIRECTORY
         else:
             output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
             os.makedirs(output_dir)
         with open(os.path.join(output_dir, "index.html"), "wb") as f:
             f.write(response.content)
Example #6
0
def test_xblock_with_handlers():
    # Tests of handler urls.
    client = Client()

    # The view sends a list of URLs to try.
    response = client.get("/view/with-handlers/")
    parsed = response.content.split(":::")
    assert_equals(len(parsed), 3)
    urls = json.loads(parsed[1])

    # These have to correspond to the urls in XBlockWithHandlers.student_view above.
    expecteds = [
        {"suffix": "", "a": "no-a", "b": "no-b"},
        {"suffix": "with_some_suffix", "a": "no-a", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "456"},
        {"suffix": "another_suffix", "a": "123", "b": "456"},
        {"suffix": "", "a": "no-a", "b": "no-b"},
        {"suffix": "with_some_suffix", "a": "no-a", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "456"},
        {"suffix": "another_suffix", "a": "123", "b": "456"},
    ]

    for url, expected in zip(urls, expecteds):
        print url  # so we can see which one failed, if any.
        response = client.get(url)
        assert_equals(response.status_code, 200)
        actual = json.loads(response.content)
        assert_equals(actual, expected)
Example #7
0
    def test_gallery_item_ajax_galleriffic(self):
        # create objects
        gallery = Gallery()
        gallery.save()
        gi_obj = GalleryImage(gallery=gallery, state="published")
        gi_obj.save()
        gi_obj.sites.add(Site.objects.get_current())
        ve_obj = VideoEmbed(gallery=gallery, state="published")
        ve_obj.save()
        ve_obj.sites.add(Site.objects.get_current())
        vf_obj = VideoFile(gallery=gallery, state="published", file="test.flv")
        vf_obj.save()
        vf_obj.sites.add(Site.objects.get_current())

        # raise 404 on invalid slug
        self.assertRaises(Http404, views.gallery_item_ajax_galleriffic, request=None, slug="invalid_slug")

        # use galleryimage template for gallery image object
        client = Client()
        response = client.get(reverse("gallery_item_ajax_galleriffic", kwargs={"slug": gi_obj.slug}))
        self.assertTemplateUsed(response, "gallery/ajax/galleriffic_galleryimage.html")

        # use videoembed template for video embed object
        response = client.get(reverse("gallery_item_ajax_galleriffic", kwargs={"slug": ve_obj.slug}))
        self.assertTemplateUsed(response, "gallery/ajax/galleriffic_videoembed.html")

        # use videofile template for video file object
        response = client.get(reverse("gallery_item_ajax_galleriffic", kwargs={"slug": vf_obj.slug}))
        self.assertTemplateUsed(response, "gallery/ajax/galleriffic_videofile.html")
Example #8
0
class UpdatesRegistrationViewsTestCase(unittest.TestCase):
    def setUp(self):
        self.c = Client()

    def tearDown(self):
        del self.c

    def test_add_a_new_email_first_time(self):
        resp = self.c.get("/register/updates/")
        self.assertEqual(200, resp.status_code)

    def test_add_a_new_email_address_complete(self):
        resp = self.c.post("/register/updates/", {"email": "johm@smith.com", "email_confirmation": "john@smith.com"})
        self.assertEqual(200, resp.status_code)

    def test_add_a_new_email_address_incomplete(self):
        resp = self.c.post("/register/updates/", {"email": "johm@smith.com"})
        self.assertEqual(200, resp.status_code)

    def test_add_a_new_email_address_password_dont_match(self):
        resp = self.c.post("/register/updates/", {"email": "johm@smith.com", "email_confirmation": "smith@smith.com"})
        self.assertEqual(200, resp.status_code)

    def test_add_a_already_existing_email_address(self):
        resp = self.c.post("/register/updates/", {"email": "johm@smith.com", "email_confirmation": "john@smith.com"})
        self.assertEqual(200, resp.status_code)
Example #9
0
class ViewTest(TestCase):
    fixtures = ["test_data.json"]

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

    def test_register_page(self):
        data = {
            "username": "test_user",
            "email": "test_user@example.com",
            "password1": "pass123",
            "password2": "pass123",
        }
        response = self.client.post("/register/", data)
        self.assertRedirects(response, "/register/success/")

    def test_blob_save(self):
        response = self.client.login(username="ButuzGOL", password="1")
        self.assertTrue(response, msg="Failed to login.")
        data = {"url": "http://www.example.com/", "title": "Test URL", "tags": "test-tag"}
        response = self.client.post("/save/", data)
        self.assertRedirects(response, "/user/ButuzGOL/")
        response = self.client.get("/user/ButuzGOL/")
        self.assertContains(response, "http://www.example.com/")
        self.assertContains(response, "Test URL")
        self.assertContains(response, "test-tag")
Example #10
0
class FeedbackTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(unicode(int(time.time())), "example@example.com", "insecure")
        self.data = {"feedback": "Your site is great.", "email": "user@example.com"}
        self.c = Client()
        self.feedback_url = reverse("django-user-feedback")

    def test_feedback_submission(self):
        response = self.c.post(self.feedback_url, self.data)
        feedback1 = Feedback.objects.latest("id")
        self.assertEqual(self.data["feedback"], feedback1.feedback)
        self.assertTrue(self.c.login(username=self.user.username, password="insecure"))
        response = self.c.post(self.feedback_url, self.data)
        feedback2 = Feedback.objects.latest("id")
        self.assertNotEqual(feedback1.id, feedback2.id)
        self.assertEqual(self.user.id, feedback2.user.id)

    @override_settings(
        TEMPLATE_CONTEXT_PROCESSORS=tuple(settings.TEMPLATE_CONTEXT_PROCESSORS)
        + ("feedback.context_processors.feedback_form",)
    )
    def test_context_processor(self):

        from django.template import loader, context

        context._standard_context_processors = None

        request = self.factory.get(self.feedback_url)
        c = RequestContext(request)
        self.assertTrue(c.has_key("feedback_form"))
        response = self.c.post(self.feedback_url, {})
        self.assertEqual(1, len(response.context["feedback_form"].errors))

        context._standard_context_processors = None
Example #11
0
class HomesiteTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.post = Blog.objects.create(title="test", text="test")
        self.message = QuickMessages.objects.create(name="test_name", email="email", message="test_message")
        self.about = About.objects.create(description="test")
        self.settings = Settings.objects.create(
            facebook="http://test.com",
            twitter="http://test.com",
            github="http://test.com",
            jabber="test@dsfdsf.com",
            icq="12123",
            email="test@dsfdsf.com",
            skype="sfsdf",
            cv="",
            linkedin="linked.in",
        )

    def test_linkedin(self):
        self.assertEqual(self.settings.linkedin, "linked.in")

    def test_home(self):
        request = self.client.get("/")
        self.assertContains(request, text="portfolio")

    def test_about(self):
        self.assertEqual(self.about.description, "test")

        request = self.client.get("/about/")
        self.assertContains(request, text="about")
        self.assertDictEqual(request.context["latest_posts"].values()[0], {"text": u"test", "id": 1, "title": u"test"})

    def test_blog(self):
        self.assertEqual(self.post.title, "test")
        self.assertEqual(self.post.text, "test")

        request = self.client.get("/blog/")
        self.assertEqual(request.context["page"], "blog")
        self.assertDictEqual(
            request.context["posts"].object_list.values()[0], {"text": u"test", "id": 1, "title": u"test"}
        )

    def test_skills(self):
        request = self.client.get("/skills/")
        self.assertContains(request, text="skills")

    def test_messages(self):
        self.assertEqual(self.message.name, "test_name")
        self.assertEqual(self.message.email, "email")
        self.assertEqual(self.message.message, "test_message")

    def test_send_message_true(self):
        request = self.client.post(
            "/ajax/quick-form",
            {"name": "test", "email": "d1ffuz0r@mail.ru", "message": "msg"},
            **{"HTTP_X_REQUESTED_WITH": "XMLHttpRequest"}
        )
        message = QuickMessages.objects.filter(message="msg").get()
        self.assertEqual(message.email, "d1ffuz0r@mail.ru")
        self.assertEqual(request.content, "Success. your message sended")
Example #12
0
def admin_client(db, admin_user):
    """A Django test client logged in as an admin user."""
    from django.test.client import Client

    client = Client()
    client.login(username=admin_user.username, password="password")
    return client
class TestCreateAnnouncement(test_case_base.TestCaseBase):
    def setUp(self):

        self.client = Client()
        self.email = "alice@eatallthecake.com"
        self.password = "shiny"
        self.houseName = "FunHouse"
        self.zipcode = 98006
        self.createUser(self.email, self.password)
        self.loginUser(self.email, self.password)
        self.createHouse(self.houseName, self.zipcode)

    def test_create_announcement(self):
        """
        Test create announcement 
        """
        ##
        expiration = "2011-01-15"
        text = "I am testing announcement text"

        # Create announcement
        response = self.client.post(
            "/dashboard/announcement/new/", data={"expiration": expiration, "text": text}, follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.redirect_chain, [("http://testserver/dashboard/", 302)])

        mail.outbox = []
        # go to dashboard page
        response = self.client.get("/dashboard/", follow=True)
        self.assertEqual(response.status_code, 200)
Example #14
0
 def test_optional_email_verification(self):
     c = Client()
     # Signup
     resp = c.post(
         reverse("account_signup"),
         {"username": "johndoe", "email": "john@doe.com", "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, ["john@doe.com"])
     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": "johndoe", "password": "johndoe"})
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL)
     self.assertEqual(mail.outbox[0].to, ["john@doe.com"])
     # 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)
Example #15
0
 def fake_incoming(self, message, connection=None):
     phone_number = "8675309" if connection == None else connection.identity
     c = Client()
     response = c.get(
         "/router/receive",
         {"backend": "test", "password": settings.ROUTER_PASSWORD, "sender": phone_number, "message": message},
     )
Example #16
0
    def test_not_duplicated(self):
        # If mozillians from the same country have different privacy_country
        # settings, make sure we don't return the country twice in the API
        # result.
        # Also, the population should be the total.

        # NOTE: There's already one Greek created in setUp()

        # Create a couple more Greeks with each privacy setting.  We should
        # still get back Greece only once.
        for i in xrange(2):
            UserFactory.create(userprofile={"country": "gr", "privacy_country": MOZILLIANS})
        for i in xrange(2):
            UserFactory.create(userprofile={"country": "gr", "privacy_country": PUBLIC})

        # One person from another country, to make sure that country shows up too.
        UserFactory.create(userprofile={"country": "us", "privacy_country": MOZILLIANS})

        client = Client()
        response = client.get(self.resource_url, follow=True)
        eq_(response.status_code, 200)
        data = json.loads(response.content)
        # We should get back Gr and Us
        eq_(data["meta"]["total_count"], 2)
        for obj in data["objects"]:
            if obj["country"] == "gr":
                # 5 greeks
                eq_(obj["population"], 5)
            else:
                # 1 USian
                eq_(obj["population"], 1)
Example #17
0
class EnableInternetNoAuthTestCase(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_no_auth_no_root(self):
        response = self.client.get("/enable_internet")

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

        self.assertEqual(json.loads(response.content)["success"], False)
        self.assertEqual(json.loads(response.content)["title"], u"Вы не авторизованы!")
        self.assertEqual(json.loads(response.content)["message"], u"Пожалуйста, авторизуйтесь повторно.")

    def test_no_auth_with_root(self):
        response = self.client.get("/enable_internet/")

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

        self.assertEqual(json.loads(response.content)["success"], False)
        self.assertEqual(json.loads(response.content)["title"], u"Вы не авторизованы!")
        self.assertEqual(json.loads(response.content)["message"], u"Пожалуйста, авторизуйтесь повторно.")

    def test_no_auth_with_root_and_ending(self):
        response = self.client.get("/enable_internet/bla_bla")

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

        self.assertEqual(json.loads(response.content)["success"], False)
        self.assertEqual(json.loads(response.content)["title"], u"Вы не авторизованы!")
        self.assertEqual(json.loads(response.content)["message"], u"Пожалуйста, авторизуйтесь повторно.")
Example #18
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse(
         "api_dispatch_detail", kwargs={"api_name": "v1", "resource_name": "users", "pk": self.user.userprofile.id}
     )
     url = urlparams(url, app_name=self.mozilla_app.name, app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data["id"], unicode(profile.id))
     eq_(data["full_name"], profile.full_name)
     eq_(data["is_vouched"], profile.is_vouched)
     eq_(data["vouched_by"], profile.vouched_by.user.id)
     eq_(data["date_vouched"], profile.date_vouched)
     eq_(data["groups"], list(profile.groups.values_list("name", flat=True)))
     eq_(data["skills"], list(profile.skills.values_list("name", flat=True)))
     eq_(data["accounts"], [{"identifier": a.identifier, "type": a.type} for a in profile.externalaccount_set.all()])
     eq_(data["bio"], profile.bio)
     eq_(data["photo"], profile.photo)
     eq_(data["ircname"], profile.ircname)
     eq_(data["country"], profile.country)
     eq_(data["region"], profile.region)
     eq_(data["city"], profile.city)
     eq_(data["date_mozillian"], profile.date_mozillian)
     eq_(data["timezone"], profile.timezone)
     eq_(data["email"], profile.email)
     eq_(data["url"], absolutify(reverse("phonebook:profile_view", args=[profile.user.username])))
Example #19
0
def test_xblock_no_student_view():
    # Try to get a response. Will try to render via WorkbenchRuntime.render;
    # since no view is provided in the XBlock, will return a Fragment that
    # indicates there is no view available.
    client = Client()
    response = client.get("/view/xblockwithoutstudentview/")
    assert_true("No such view" in response.content)
Example #20
0
 def test_request_with_huge_limit(self):
     client = Client()
     url = urlparams(self.mozilla_resource_url, limit=200000000000000000000)
     response = client.get(url, follow=True)
     eq_(response.status_code, 200)
     data = json.loads(response.content)
     eq_(data["meta"]["limit"], 1)
Example #21
0
class SimpleTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_nav_home(self):
        # Issue a GET request to the Home page.
        response = self.client.get("/")

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

        # Check that the home.html template is being used.
        self.assertTemplateUsed(response, "home.html")

        # Check that the home page is 'selected'.
        self.assertContains(response, '<li class="selected"><a href="/" rel="home" accesskey="1">Home' "</a></li>")

        # Check that the about page is not 'selected'.
        self.assertContains(response, '<li><a href="/about/">About</a></li>')

    def test_nav_about(self):
        # Issue a GET request to the Home page.
        response = self.client.get("/about/")

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

        # Check that the home.html template is being used.
        self.assertTemplateUsed(response, "about.html")

        # Check that the home page is not 'selected'.
        self.assertContains(response, '<li><a href="/" rel="home" accesskey="1">Home</a></li>')

        # Check that the about page is 'selected'.
        self.assertContains(response, '<li class="selected"><a href="/about/">About</a></li>')
Example #22
0
 def test_filtering(self, filter_mock):
     url = urlparams(self.resource_url, city="athens")
     client = Client()
     client.get(url, follow=True)
     ok_(filter_mock.called)
     call_arg = filter_mock.call_args[0][0]
     eq_(call_arg.children, [("city__iexact", "athens")])
Example #23
0
    def test_get_salt_with_wrong_csrf_token(self):
        settings.DEBUG = True
        user = self._get_user("normal")
        username = user.username
        user_profile = user.get_profile()
        salt = user_profile.sha_login_salt

        csrf_client = Client(enforce_csrf_checks=True)

        # Create session
        response = csrf_client.get("/?auth=login", HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        sessionid = response.cookies["sessionid"]

        # send POST with sessionid but with wrong csrf token
        response = csrf_client.post(
            "/?auth=get_salt",
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
            HTTP_COOKIE=("%s=1234567890abcdef1234567890abcdef;" "sessionid=%s")
            % (settings.CSRF_COOKIE_NAME, sessionid),
            data={"username": username},
        )
        self.assertResponse(
            response,
            must_contain=("Forbidden", "CSRF verification failed.", "CSRF token missing or incorrect."),
            must_not_contain=(salt, "Traceback", "Form errors", "field is required"),
        )
Example #24
0
class testTagsPage(TestCase):
    def setUp(self):
        self.client = Client()
        self.dom = ""

    def tearDown(self):
        self.dom = ""

    def __load_dom(self):
        response = self.client.get("/tags/")
        self.dom = html.fromstring(response.content)

    def testTagsPageResponse(self):
        response = self.client.get("/tags/")
        self.failUnlessEqual(response.status_code, 200)

    def testTagsPageShouldShowTags(self):
        self.tags = create_multiple_test_tags()
        self.__load_dom()
        tags_list = self.dom.cssselect("#tags-list li")
        assert len(tags_list), 100

    def testTagsPageShouldHaveLinkToGoBackToTheHomePage(self):
        self.__load_dom()
        home_link = self.dom.cssselect("p.back a")
        assert len(home_link), 1
        assert home_link[0].text, "&larr; go back to the home page"
        assert home_link[0].attrib["href"], "/"

    def testTagNameShouldHaveQuotesCount(self):
        self.tags = create_multiple_test_tags()
        self.__load_dom()
        assert self.dom.cssselect("#tags-list li a")[0].text, "Tag 0 (10)"
Example #25
0
class TestUrlPatterns(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_redirect(self):
        response = self.client.get("/en-US/gloubi-boulga/")
        eq_(response.status_code, 301)
        eq_(response["Location"], "http://testserver/en-US/mock/view/")

    def test_temporary_redirect(self):
        response = self.client.get("/en-US/gloubi-boulga/tmp/")
        eq_(response.status_code, 302)
        eq_(response["Location"], "http://testserver/en-US/mock/view/")

    def test_external_redirect(self):
        response = self.client.get("/en-US/gloubi-boulga/ext/")
        eq_(response.status_code, 301)
        eq_(response["Location"], "https://marketplace.firefox.com")

    def test_callable_redirect(self):
        response = self.client.get("/en-US/gloubi-boulga/call/")
        eq_(response.status_code, 301)
        eq_(response["Location"], "http://testserver/qwer")

        response = self.client.get("/en-US/gloubi-boulga/call/?test=1")
        eq_(response.status_code, 301)
        eq_(response["Location"], "http://testserver/asdf")
Example #26
0
class HeartbeatTestCase(ModuleStoreTestCase):
    """
    Test the heartbeat
    """

    def setUp(self):
        self.client = Client()
        self.heartbeat_url = reverse("heartbeat")
        return super(HeartbeatTestCase, self).setUp()

    def test_success(self):
        response = self.client.get(self.heartbeat_url)
        self.assertEqual(response.status_code, 200)

    def test_sql_fail(self):
        with patch("heartbeat.views.connection") as mock_connection:
            mock_connection.cursor.return_value.execute.side_effect = DatabaseError
            response = self.client.get(self.heartbeat_url)
            self.assertEqual(response.status_code, 503)
            response_dict = json.loads(response.content)
            self.assertIn("SQL", response_dict)

    def test_modulestore_fail(self):
        with patch("heartbeat.views.modulestore") as mock_modulestore:
            mock_modulestore.return_value.heartbeat.side_effect = HeartbeatFailure("msg", "service")
            response = self.client.get(self.heartbeat_url)
            self.assertEqual(response.status_code, 503)
Example #27
0
    def test_ajax_vote(self):
        """
            Test voting for the character
        """
        self.initialize()

        client = Client()

        client.login(username=self.u1.username, password="secret")

        # sending vote
        response = client.post(
            self.game1.get_absolute_url() + "/json/",
            {"game_id": self.game1.id, "character_id": self.game1.character1.id},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )

        self.failUnlessEqual(response.status_code, 200)

        # if vote was succesfull recive user avatar
        response = client.get(
            "/" + urls["CONTEST_VOTE_AJAX"] + "/" + str(self.u1.id) + "/", HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )

        self.failUnlessEqual(response.status_code, 200)
Example #28
0
    def test_purchase(self):
        """
        Tests purchase handler
        """
        c = Client()
        time = str(datetime.now())
        jsonstr = json.dumps(
            {"time": time, "merchant": {"id": 1}, "dollar_amount": 20.50, "description": "test purchase"}
        )
        response = c.post("/api/users/2/purchase", jsonstr, "application/json", **self.extra)
        # print response.content
        self.assertEqual("Created", response.content, "")

        """
        [
            {
                "dollar_amount": "20.5", 
                "merchant": {
                    "name": "Safeway"
                }, 
                "description": "test purchase", 
                "time": "2011-09-30 23:49:03"
            }
        ]
        """
        response = c.get("/api/users/2/purchase", **self.extra)
        # print response.content
        r = json.loads(response.content)
        self.assertEqual(1, len(r), "")
        self.assertEqual("test purchase", r[0]["description"], "")
        self.assertEqual("Safeway", r[0]["merchant"]["name"], "")

        response = c.delete("/api/users/2/purchase", **self.extra)
        # print response.content
        self.assertEqual(0, len(response.content), "")
Example #29
0
 def test_bad_url(self):
     dummy_cache = cache.get_cache("django.core.cache.backends.dummy.DummyCache")
     with patch.object(models, "cache", dummy_cache):
         c = Client()
         bad_url = "%s/image/aa" % self.url
         response = c.delete(bad_url)
         self.assertEquals(response.status_code, 404, "Rejects an invalid url")
Example #30
0
    def test_make_request(self):
        " Make a request authenticated with Token."

        token = Token.objects.create(self.user)
        client = Client()
        response = client.get("/items", HTTP_X_AUTH_TEST_TOKEN=token.token)
        self.assertEqual(response.status_code, 200)