def _test_update_content(self):
        """Fetches an existing Content object and updates that sucker."""
        client = Client()
        client.login(username="******", password="******")
        new_data = self.updated_data()

        content_detail_url = reverse("content-detail",
                                     kwargs={"pk": self.content.id})

        response = client.get(content_detail_url)
        self.assertEqual(response.status_code, 200)
        # Squirt in some new data
        content_data = response.data
        content_data.update(new_data)
        # PUT it up
        data = json.dumps(content_data, cls=JsonEncoder)
        response = client.put(content_detail_url,
                              data=data,
                              content_type="application/json")
        # no permissions, no PUTing
        self.assertEqual(response.status_code, 403)
        self.give_permissions()
        # ok, PUT it now
        response = client.put(content_detail_url,
                              data=data,
                              content_type="application/json")
        if response.status_code != 200:
            print(response.content)
        self.assertEqual(response.status_code, 200)

        # Check that it returns an instance with the new data
        # And check that the detail view is also correct
        response = client.get(content_detail_url)
        self.assertEqual(response.status_code, 200)
        self.check_response_data(response.data, new_data)
Exemple #2
0
class HttpTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.sites = SitesCollection()
        # For each test case, test site must exist, so it can be set
        # by SetSiteMiddleware
        self.site = self.sites.create_item(SINGLE_SITE_ID)
        self.site.aliases.create_item(TEST_SITE)

    def post(self, url, args):
        return self.client.post(url,
                                json.dumps(args),
                                'application/json; charset=UTF-8',
                                HTTP_SITE_URL=TEST_SITE)

    """ To be used for views that are not contacted via Ajax. """

    def post_form(self, url, args):
        return self.client.post(url, args)

    def get(self, url, **extra_headers):
        return self.client.get(url, HTTP_SITE_URL=TEST_SITE, **extra_headers)

    def put(self, url, args=None):
        if args is None:
            return self.client.put(url, HTTP_SITE_URL=TEST_SITE)
        return self.client.put(url,
                               data=json.dumps(args),
                               content_type='application/json;  charset=UTF-8',
                               HTTP_SITE_URL=TEST_SITE)

    def delete(self, url):
        return self.client.delete(url, HTTP_SITE_URL=TEST_SITE)
Exemple #3
0
    def test_valid_json_but_invalid_extended_info(self):
        with self.settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.all_ok',
                           SPOTSEEKER_SPOT_FORM='spotseeker_server.org_forms.uw_spot.UWSpotForm'):
            c = Client()
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 20

            response = c.get(self.url)
            etag = response["ETag"]

            json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"true","has_computers":"true","num_computers":"10","manager":"Sam","organization":"UW"}}' % (new_name, new_capacity)
            response = c.put(self.url, json_string, content_type="application/json", If_Match=etag)
            self.assertEquals(response.status_code, 200, "Accepts a valid json string")

            # test: invalid extended info value
            response = c.get(self.url)
            etag = response["ETag"]
            updated_json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"wub wub wub wu wu wuhhhh WUB WUB WUBBBBUB", "has_computers":"true", "num_computers":"10","manager":"Sam","organization":"UW"}}' % (new_name, new_capacity)

            response = c.put(self.url, updated_json_string, content_type="application/json", If_Match=etag)
            self.assertEquals(response.status_code, 400, "Doesn't update spot info with invalid extended info")

            response = c.get(self.url)
            self.assertEquals(json.loads(json_string)['extended_info'], json.loads(response.content)['extended_info'], "Doesn't update spot info with invalid extended info")
            
            # test: invalid int value
            invalid_int = "invalid_int"
            invalid_int_json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"true", "has_computers":"true", "num_computers":"%s","manager":"Sam","organization":"UW"}}' % (new_name, new_capacity, invalid_int)

            response = c.put(self.url, invalid_int_json_string, content_type="application/json", If_Match=etag)
            self.assertEquals(response.status_code, 400, "Doesn't update spot info with invalid int value")

            response = c.get(self.url)
            self.assertEquals(json.loads(json_string)['extended_info'], json.loads(response.content)['extended_info'], "Doesn't update spot info with invalid int value")
Exemple #4
0
    def test_map_json(self):
        c = Client()
        # Test that saving a map when not logged in gives 401
        response = c.put(
            reverse(
                'map_json',
                args=(
                    '1',
                )),
            data=self.viewer_config,
            content_type="text/json")
        self.assertEqual(response.status_code, 401)

        c.login(username=self.user, password=self.passwd)
        response = c.put(
            reverse(
                'map_json',
                args=(
                    '1',
                )),
            data=self.viewer_config_alternative,
            content_type="text/json")
        self.assertEqual(response.status_code, 200)

        map_obj = Map.objects.get(id=1)
        self.assertEquals(map_obj.title, "Title2")
        self.assertEquals(map_obj.abstract, "Abstract2")
        self.assertEquals(map_obj.layer_set.all().count(), 1)
	def test_put(self):
		race = RaceFactory.produce()
		point = PointFactory.produce(race)
		team = TeamFactory.produce(race)
		
		client = Client()
		token = AuthTokenFactory.produce(point)
		
		# no token
		response = client.put('/api/log/')
		self.assertEqual(response.status_code, 403)
		
		# good input
		# d = now()
		# timestamp = int(mktime(d.timetuple()))*1000
		t = int(time()*1000)
		d = datetime.fromtimestamp(t/1000.0)
		d = d.replace(tzinfo=pytz.UTC)
		timestamp = t
		body = ('{"team_id":'+ str(team.pk) +','
				' "event_type":"ARR",'
				' "timestamp":'+ str(timestamp) +','
				' "is_successful":false}')
		response = client.put('/api/log/', body, HTTP_RACEPOINT_TOKEN=token.token)
		self.assertEqual(response.status_code, 200)
		
		event = LogEvent.objects.latest('created')
		self.assertEqual(event.point.pk, point.pk)
		self.assertEqual(event.event_type, 'ARR')
		self.assertEqual(event.timestamp, d)
		self.assertEqual(event.is_successful, False)
		body = read_json(response.content)
		self.assertEqual(event.pk, body['id'])
    def _test_update_content(self):
        """Fetches an existing Content object and updates that sucker."""
        client = Client()
        client.login(username="******", password="******")
        new_data = self.updated_data()

        content_detail_url = reverse("content-detail", kwargs={"pk": self.content.id})

        response = client.get(content_detail_url)
        self.assertEqual(response.status_code, 200)
        # Squirt in some new data
        content_data = response.data
        content_data.update(new_data)
        # PUT it up
        data = json.dumps(content_data, cls=JsonEncoder)
        response = client.put(content_detail_url, data=data, content_type="application/json")
        # no permissions, no PUTing
        self.assertEqual(response.status_code, 403)
        self.give_permissions()
        # ok, PUT it now
        response = client.put(content_detail_url, data=data, content_type="application/json")
        if response.status_code != 200:
            print(response.content)
        self.assertEqual(response.status_code, 200)

        # Check that it returns an instance with the new data
        # And check that the detail view is also correct
        response = client.get(content_detail_url)
        self.assertEqual(response.status_code, 200)
        self.check_response_data(response.data, new_data)
Exemple #7
0
    def test_map_json(self):
        c = Client()
        # Test that saving a map when not logged in gives 401
        response = c.put(
            reverse(
                'map_json',
                args=(
                    '1',
                )),
            data=self.viewer_config,
            content_type="text/json")
        self.assertEqual(response.status_code, 401)

        c.login(username=self.user, password=self.passwd)
        response = c.put(
            reverse(
                'map_json',
                args=(
                    '1',
                )),
            data=self.viewer_config_alternative,
            content_type="text/json")
        self.assertEqual(response.status_code, 200)

        map_obj = Map.objects.get(id=1)
        self.assertEquals(map_obj.title, "Title2")
        self.assertEquals(map_obj.abstract, "Abstract2")
        self.assertEquals(map_obj.layer_set.all().count(), 1)
Exemple #8
0
class ViewTests(Base4StoreTest):
    kbfixtures = ["ace.n3", "melissa.rdf"]
    urls = "fourstore.test_urls"

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

    def test_sparql_proxy(self):
        response = self.client.post("/sparql/",
                                    urllib.urlencode({"query":TEST_SPARQL}),
                                    content_type="application/x-www-form-urlencoded",
                                    HTTP_ACCEPT="application/json")
        self.assertEquals(TEST_JSON_RESPONSE, json.loads(response.content))

    def test_sparql_proxy_http_verbs(self):
        response = self.client.put("/sparql/",
                                   urllib.urlencode({"query":TEST_SPARQL}),
                                   content_type="application/x-www-form-urlencoded")
        self.assertEquals(400, response.status_code)

        response = self.client.delete("/sparql/")
        self.assertEquals(400, response.status_code)

    def test_sparql_proxy_bad_content_type(self):
        response = self.client.put("/sparql/", {"query":TEST_SPARQL})
        self.assertEquals(400, response.status_code)
Exemple #9
0
class HttpTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.sites = SitesCollection()
        # For each test case, test site must exist, so it can be set
        # by SetSiteMiddleware
        self.site = self.sites.create_item(SINGLE_SITE_ID)
        self.site.aliases.create_item(TEST_SITE)

    def post(self, url, args):
        return self.client.post(
            url, json.dumps(args), 'application/json; charset=UTF-8',
            HTTP_SITE_URL=TEST_SITE)

    """ To be used for views that are not contacted via Ajax. """
    def post_form(self, url, args):
        return self.client.post(url, args)

    def get(self, url, **extra_headers):
        return self.client.get(url, HTTP_SITE_URL=TEST_SITE, **extra_headers)

    def put(self, url, args=None):
        if args is None:
            return self.client.put(url, HTTP_SITE_URL=TEST_SITE)
        return self.client.put(
            url, data=json.dumps(args),
            content_type='application/json;  charset=UTF-8',
            HTTP_SITE_URL=TEST_SITE)


    def delete(self, url):
        return self.client.delete(url, HTTP_SITE_URL=TEST_SITE)
Exemple #10
0
    def test_a_valid_image_no_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            with self.settings(MEDIA_ROOT=self.TEMP_DIR):
                c = Client()
                #GIF
                f = open("%s/../resources/test_gif2.gif" % TEST_ROOT)
                new_gif_name = "testing PUT name: {0}".format(random.random())
                response = c.put(self.gif_url, {
                    "description": new_gif_name,
                    "image": f
                })
                self.assertEquals(response.status_code, 400,
                                  "Bad request w/o an etag")

                updated_img = SpotImage.objects.get(pk=self.gif.pk)
                self.assertEquals(updated_img.image, self.gif.image,
                                  "No etag - same image")

                #JPEG
                f = open("%s/../resources/test_jpeg2.jpg" % TEST_ROOT)
                new_jpeg_name = "testing PUT name: {0}".format(random.random())
                response = c.put(self.gif_url, {
                    "description": new_jpeg_name,
                    "image": f
                })
                self.assertEquals(response.status_code, 400,
                                  "Bad request w/o an etag")

                updated_img = SpotImage.objects.get(pk=self.jpeg.pk)
                self.assertEquals(updated_img.description,
                                  self.jpeg.description,
                                  "No etag - same image")

                #PNG
                f = open("%s/../resources/test_png2.png" % TEST_ROOT)
                new_png_name = "testing PUT name: {0}".format(random.random())
                response = c.put(self.gif_url, {
                    "description": new_png_name,
                    "image": f
                })
                self.assertEquals(response.status_code, 400,
                                  "Bad request w/o an etag")

                updated_img = SpotImage.objects.get(pk=self.png.pk)
                self.assertEquals(updated_img.description,
                                  self.png.description, "No etag - same image")

                response = c.get(self.gif_url)
                content_length = response["content-length"]
                self.assertNotEqual(
                    os.fstat(f.fileno()).st_size, int(content_length),
                    "Content length doesn't match new png")

                f = open("%s/../resources/test_gif.gif" % TEST_ROOT)
                self.assertEquals(
                    os.fstat(f.fileno()).st_size, int(content_length),
                    "Content length does match original gif")
    def test_single_get(self):
        user, created = User.objects.get_or_create(username="******")
        self.assertEquals(created, True)

        spot1 = Spot.objects.create(name="This is for testing Fav 8")
        spot2 = Spot.objects.create(name="This is for testing Fav 9")
        spot3 = Spot.objects.create(name="This is for testing Fav 10")

        c = Client()
        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 0, "No initial favorites")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, False, "Not a fav")

        url = "/api/v1/user/me/favorite/%s" % spot3.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, False, "Not a fav")

        url = "/api/v1/user/me/favorite/%s" % spot3.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "Another favorite added")

        spot1.delete()
        spot2.delete()
        spot3.delete()
Exemple #12
0
    def test_single_get(self):
        user, created = User.objects.get_or_create(username="******")
        self.assertEquals(created, True)

        spot1 = Spot.objects.create(name="This is for testing Fav 8")
        spot2 = Spot.objects.create(name="This is for testing Fav 9")
        spot3 = Spot.objects.create(name="This is for testing Fav 10")

        c = Client()
        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 0, "No initial favorites")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, False, "Not a fav")

        url = "/api/v1/user/me/favorite/%s" % spot3.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, False, "Not a fav")

        url = "/api/v1/user/me/favorite/%s" % spot3.pk
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorite = json.loads(response.content)
        self.assertEquals(favorite, True, "Another favorite added")

        spot1.delete()
        spot2.delete()
        spot3.delete()
    def test_no_duplicate_extended_info(self):
        dummy_cache = cache.get_cache("django.core.cache.backends.dummy.DummyCache")
        with patch.object(models, "cache", dummy_cache):
            c = Client()
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 30

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "true"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag,
            )

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "true"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag,
            )

            self.assertEquals(
                len(self.spot.spotextendedinfo_set.filter(key="has_a_funky_beat")),
                1,
                "Only has 1 has_a_funky_beat SpotExtendedInfo object after 2 PUTs",
            )

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "of_course"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag,
            )

            self.assertEquals(
                len(self.spot.spotextendedinfo_set.filter(key="has_a_funky_beat")),
                1,
                "Only has 1 has_a_funky_beat SpotExtendedInfo object after 3 PUTs",
            )
            self.assertEquals(
                self.spot.spotextendedinfo_set.get(key="has_a_funky_beat").value,
                "of_course",
                "SpotExtendedInfo was updated to the latest value on put.",
            )
Exemple #14
0
    def test_a_valid_image_no_etag(self):
        with self.settings(MEDIA_ROOT=self.TEMP_DIR):
            c = Client()
            # GIF
            f = open("%s/../resources/test_gif2.gif" % TEST_ROOT)
            new_gif_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={
                                 "description": new_gif_name,
                                 "image": f
                             },
                             content_type="image/gif")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.gif.pk)
            self.assertEquals(updated_img.image, self.gif.image)

            # JPEG
            f = open("%s/../resources/test_jpeg2.jpg" % TEST_ROOT)
            new_jpeg_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={
                                 "description": new_jpeg_name,
                                 "image": f
                             },
                             content_type="image/jpeg")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.jpeg.pk)
            self.assertEquals(updated_img.description, self.jpeg.description)

            # PNG
            f = open("%s/../resources/test_png2.png" % TEST_ROOT)
            new_png_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={
                                 "description": new_png_name,
                                 "image": f
                             },
                             content_type="image/png")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.png.pk)
            self.assertEquals(updated_img.description, self.png.description)

            response = c.get(self.gif_url)
            content_length = response["content-length"]
            self.assertNotEqual(
                os.fstat(f.fileno()).st_size, int(content_length))

            f = open("%s/../resources/test_gif.gif" % TEST_ROOT)
            self.assertEquals(
                os.fstat(f.fileno()).st_size, int(content_length))
Exemple #15
0
    def test_no_duplicate_extended_info(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 30

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "true"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag)

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "true"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag)

            self.assertEquals(
                len(
                    self.spot.spotextendedinfo_set.filter(
                        key="has_a_funky_beat")), 1,
                'Only has 1 has_a_funky_beat SpotExtendedInfo object after 2 PUTs'
            )

            response = c.get(self.url)
            etag = response["ETag"]
            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30}, "extended_info": {"has_a_funky_beat": "of_course"} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag)

            self.assertEquals(
                len(
                    self.spot.spotextendedinfo_set.filter(
                        key="has_a_funky_beat")), 1,
                'Only has 1 has_a_funky_beat SpotExtendedInfo object after 3 PUTs'
            )
            self.assertEquals(
                self.spot.spotextendedinfo_set.get(
                    key="has_a_funky_beat").value, 'of_course',
                'SpotExtendedInfo was updated to the latest value on put.')
Exemple #16
0
def crud_operations(client: Client, client_data, client_updated_data, path,
                    select_model):
    client.post(reverse(f"{path}-list"), data=client_data)
    assert select_model.objects.exists()
    client.put(reverse(f"{path}-detail", kwargs={"pk": "1"}),
               data=client_updated_data,
               content_type="application/json")
    updated_data = model_to_dict(select_model.objects.first())
    updated_data.pop("id")
    assert updated_data == client_updated_data
    client.delete(reverse(f"{path}-detail", kwargs={"pk": "1"}),
                  data=client_updated_data,
                  content_type="application/json")
    assert not select_model.objects.exists()
    def test_put(self):
        user, created = User.objects.get_or_create(username="******")
        self.assertEquals(created, True)

        spot1 = Spot.objects.create(name="This is for testing Fav 4")
        spot2 = Spot.objects.create(name="This is for testing Fav 5")

        c = Client()
        c.login(username="******")
        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 0, "No initial favorites")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 1, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 1, "No double dipping")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 2, "Both added")

        spot1.delete()
        spot2.delete()
Exemple #18
0
    def test_put(self):
        user, created = User.objects.get_or_create(username="******")
        self.assertEquals(created, True)

        spot1 = Spot.objects.create(name="This is for testing Fav 4")
        spot2 = Spot.objects.create(name="This is for testing Fav 5")

        c = Client()
        c.login(username="******")
        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 0, "No initial favorites")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 1, "One favorite added")

        url = "/api/v1/user/me/favorite/%s" % spot1.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 1, "No double dipping")

        url = "/api/v1/user/me/favorite/%s" % spot2.pk
        response = c.put(url,
                         "True",
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        url = "/api/v1/user/me/favorites"
        response = c.get(url, TESTING_OAUTH_USER="******")
        favorites = json.loads(response.content)
        self.assertEquals(len(favorites), 2, "Both added")

        spot1.delete()
        spot2.delete()
Exemple #19
0
class TruthTest(TestCase):
    fixtures = ['testdata.json']

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

    def test_get_dhcp_scope_by_name(self):
        resp = self.client.get('/api/keyvalue/?keystore=phx-vlan73', follow=True)
        obj = json.loads(resp.content)
        self.assertEqual(obj['dhcp.scope.start'],'10.0.1.0')
        self.assertEqual(obj['dhcp.scope.end'],'10.0.1.255')

    def test_output_dhcp_config(self):
        resp = self.client.get('/dhcp/showfile/1', follow=True)
        #print resp
        #print resp.status_code
        #print resp.content
    def test_get_dhcp_scopes_by_api(self):
        resp = self.client.get('/api/keyvalue/?key=is_dhcp_scope', follow=True)
        obj = json.loads(resp.content)
        self.assertEqual(2,len(obj))
        self.assertEqual(obj['truth:phx-vlan73:is_dhcp_scope'], 'True')
        self.assertEqual(obj['truth:test:is_dhcp_scope'], 'False')

    def test_get_dhcp_key_value(self):
        dhcp_scope = 'phx-vlan73'
        resp = self.client.get('/api/keyvalue/?keystore=%s' % dhcp_scope, follow=True)
        obj = json.loads(resp.content)
        #self.assertEqual(2,len(obj))
        #self.assertEqual(obj['truth:phx-vlan73:is_dhcp_scope'], 'True')
        #self.assertEqual(obj['truth:test:is_dhcp_scope'], 'True')

    def test_dhcp_scope_names_and_descriptions(self):
        dhcp_scope = 'phx-vlan73'
        resp = self.client.get('/api/v2/dhcp/%s/get_scopes_with_names/' % dhcp_scope, follow=True)
        obj = json.loads(resp.content)
        self.assertEqual(obj[0]['name'], 'phx-vlan73')
        self.assertEqual(obj[0]['description'], 'PHX Vlan 73 DHCP Scope')

    def test_update_dhcp_scope_value(self):
        dhcp_scope = 'phx-vlan73'
        resp = self.client.put('/en-US/api/keyvalue/%s/' % dhcp_scope, {'key':'dhcp.scope.start', 'value':'1.1.1.1'})
        resp = self.client.put('/en-US/api/keyvalue/%s/' % dhcp_scope, {'key':'dhcp.scope.start2', 'value':'9.9.9.9'})
        if resp.status_code == 404:
            #print 'does not exist'
            resp = self.client.post('/api/keyvalue/%s/' % dhcp_scope, {'key':'dhcp.scope.start2', 'value':'9.9.9.9', 'truth_name':dhcp_scope})
            #print resp.content
        resp = self.client.get('/api/keyvalue/?keystore=%s' % dhcp_scope, follow=True)
        obj = json.loads(resp.content)
    def test_a_valid_image_no_etag(self):
        with self.settings(MEDIA_ROOT=self.TEMP_DIR):
            c = Client()
            # GIF
            f = open("%s/../resources/test_gif2.gif" % TEST_ROOT)
            new_gif_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={"description": new_gif_name,
                                    "image": f},
                             content_type="image/gif")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.gif.pk)
            self.assertEquals(updated_img.image, self.gif.image)

            # JPEG
            f = open("%s/../resources/test_jpeg2.jpg" % TEST_ROOT)
            new_jpeg_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={"description": new_jpeg_name,
                                    "image": f},
                             content_type="image/jpeg")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.jpeg.pk)
            self.assertEquals(updated_img.description,
                              self.jpeg.description)

            # PNG
            f = open("%s/../resources/test_png2.png" % TEST_ROOT)
            new_png_name = "testing PUT name: {0}".format(random.random())
            response = c.put(self.gif_url,
                             files={"description": new_png_name,
                                    "image": f},
                             content_type="image/png")
            self.assertEquals(response.status_code, 400)

            updated_img = ItemImage.objects.get(pk=self.png.pk)
            self.assertEquals(updated_img.description,
                              self.png.description)

            response = c.get(self.gif_url)
            content_length = response["content-length"]
            self.assertNotEqual(os.fstat(f.fileno()).st_size,
                                int(content_length))

            f = open("%s/../resources/test_gif.gif" % TEST_ROOT)
            self.assertEquals(os.fstat(f.fileno()).st_size,
                              int(content_length))
Exemple #21
0
    def test_map_json(self):
        c = Client()

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

        c.login(username="******", password="******")
        response = c.put("/maps/1/data",data=MapTest.viewer_config_alternative,content_type="text/json")
        self.assertEqual(response.status_code,204)

        map_obj = Map.objects.get(id=1)
        self.assertEquals(map_obj.title, "Title2")
        self.assertEquals(map_obj.abstract, "Abstract2")
        self.assertEquals(map_obj.layer_set.all().count(), 1)
Exemple #22
0
class TestNotices(TestCase):
    def setUp(self):
        self.client = Client()

    @skipIf(missing_url("myuw_home"), "myuw urls not configured")
    def test_javerage_books(self):
        url = reverse("myuw_notices_api")
        get_user('javerage')
        self.client.login(username='******',
                          password=get_user_pass('javerage'))
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)

        self.assertEquals(len(data), 23)

        self.assertEquals(data[0]["is_read"], False)

        hash_value = data[0]["id_hash"]

        response = self.client.put(
            url,
            data='{"notice_hashes":["%s"]}' % hash_value)

        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.content, '')

        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)

        self.assertEquals(len(data), 23)

        match = False
        for el in data:
            if el["id_hash"] == hash_value:
                match = True
                self.assertEquals(el["is_read"], True)

        self.assertEquals(match, True)

        response = self.client.put(
            url, data='{"notice_hashes":["fake-fake-fake"]}')

        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.content, '')
Exemple #23
0
class CourseCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_course_detail(self):
        put = { 'name'   :   "test",
                'description': 'test',
                'grade' : 2009,
                'grade_point': 5,
               }
        
        response = self.client.put("/score/course/crud/", json.dumps(put), "text")
        self.assertEqual(response.content, '1')
        course = Course.objects.get(pk=1)
        self.assertEqual(course.description, "test")
        
        post = {'name' : "test2"}
        response = self.client.post("/score/course/crud/%d" % course.pk, json.dumps(post), "text")
        self.assertEqual(response.content, '"success"')
        course = Course.objects.filter(name="test2")[0]
        self.assertEqual(course.description, "test")    
        
        response = self.client.get("/score/course/crud/%d" % course.pk)
        s = json.loads(response.content)[0]
        self.assertEqual("test2", s["fields"]["name"])
        
        response = self.client.delete("/score/course/crud/%d" % course.pk)
        course = Course.objects.filter(name="test2")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(course))
Exemple #24
0
    def test_hours(self):
        spot = Spot.objects.create(name="This spot has available hours")
        etag = spot.etag

        put_obj = {
            'name': "This spot has available hours",
            'capacity': "4",
            'location': {
                'latitude': '55',
                'longitude': '30',
            },
            'available_hours': {
                'monday': [["00:00", "10:00"], ["11:00", "14:00"]],
                'tuesday': [["11:00", "14:00"]],
                'wednesday': [["11:00", "14:00"]],
                'thursday': [["11:00", "14:00"]],
                'friday': [["11:00", "14:00"]],
                'saturday': [],
                'sunday': [["11:00", "14:00"]],
            }
        }

        client = Client()
        url = "/api/v1/spot/%s" % spot.pk
        response = client.put(url,
                              json.dumps(put_obj),
                              content_type="application/json",
                              If_Match=etag)
        spot_dict = json.loads(response.content)

        self.maxDiff = None
        self.assertEquals(
            spot_dict["available_hours"], put_obj["available_hours"],
            "Data from the web service matches the data for the spot")
Exemple #25
0
    def get_response(self, url, request_type, data={}, status=200, params_string=''):
        c = Client()
        request_url = '/database/' + url + params_string

        if request_type == 'post':
            response = c.post(
                request_url,
                data,
            )
        elif request_type == 'get':
            response = c.get(
                request_url,
                data,
            )
        elif request_type == 'delete':
            response = c.delete(
                request_url,
                data,
            )
        elif request_type == 'put':
            response = c.put(
                request_url,
                data,
            )

        self.assertEqual(status, response.status_code)
        if response.content and status == 200:
            return json.loads(response.content)
    def test_valid_different_image_type_valid_etag(self):
        with self.settings(MEDIA_ROOT=self.TEMP_DIR):
            c = Client()
            response = c.get(self.gif_url)

            etag = response["etag"]

            f = open("%s/../resources/test_png.png" % TEST_ROOT)
            f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT)

            new_name = "testing PUT name: {0}".format(random.random())

            response = c.put(self.gif_url,
                             files={"description": new_name,
                                    "image": f},
                             content_type="multipart/form-data; "
                                          "boundary=--aklsjf--",
                             If_Match=etag)
            self.assertEquals(response.status_code, 200)
            f = open("%s/../resources/test_png.png" % TEST_ROOT)

            # Just to be sure
            response = c.get(self.gif_url)
            self.assertEquals(response["content-type"], "image/png")
            self.assertEquals(int(response["content-length"]),
                              len(f.read()))
            self.assertNotEqual(int(response["content-length"]),
                                len(f2.read()))
Exemple #27
0
class MessageCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        a = self.client.login(username="******", password="******")
        
    def test_get_message_list(self):
        pass
        
    def test_message_detail(self):
        put = { 'message'   :   "test",
                'to_user'  :   1,
               }
        
        response = self.client.put("/message/crud/", json.dumps(put), "text")
        self.assertEqual(response.content, '1')
        message = Message.objects.filter(message="test")[0]
        self.assertEqual(message.to_user.pk, 1)
        
        post = {'message' : "test2"}
        response = self.client.post("/message/crud/%d" % message.pk, json.dumps(post), "text")
        message = Message.objects.filter(message="test2")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(message.message, "test2")
        
        
        response = self.client.get("/message/crud/%d" % message.pk)
        f = json.loads(response.content)[0]
        self.assertEqual("test2", f["fields"]["message"])
        
        response = self.client.delete("/message/crud/%d" % message.pk)
        message = Message.objects.filter(pk=message.pk)
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(message))
        
Exemple #28
0
 def test_invalid_url(self):
     with self.settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.all_ok',
                        MEDIA_ROOT=self.TEMP_DIR):
         c = Client()
         bad_url = "%s/image/aa" % self.url
         response = c.put(bad_url, '{}', content_type="application/json")
         self.assertEquals(response.status_code, 404, "Rejects a non-numeric url")
Exemple #29
0
    def test_put_trusted_client_no_user(self):
        dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            consumer_name = "Trusted test consumer"

            key = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()
            secret = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()

            create_consumer = Consumer.objects.create(name=consumer_name, key=key, secret=secret)
            trusted_consumer = TrustedOAuthClient.objects.create(consumer=create_consumer, is_trusted=True)

            consumer = oauth2.Consumer(key=key, secret=secret)

            req = oauth2.Request.from_consumer_and_token(consumer, None, http_method='GET', http_url="http://testserver/api/v1/spot/%s" % self.spot.pk)

            oauth_header = req.to_header()
            c = Client()

            response = c.get(self.url, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            etag = response["ETag"]

            spot_dict = json.loads(response.content)
            spot_dict['name'] = "Failing to modify oauth"

            response = c.put(self.url, json.dumps(spot_dict), content_type="application/json", If_Match=etag, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            self.assertEquals(response.status_code, 401, "Rejects a PUT from a trusted oauth client w/o a given user")
Exemple #30
0
    def test_valid_json_outdated_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 30

            response = c.get(self.url)
            etag = response["ETag"]

            intermediate_spot = Spot.objects.get(pk=self.spot.pk)
            intermediate_spot.name = "This interferes w/ the PUT"
            intermediate_spot.save()

            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag)
            self.assertEquals(response.status_code, 409,
                              "An outdated etag leads to a conflict")

            updated_spot = Spot.objects.get(pk=self.spot.pk)
            self.assertEquals(
                updated_spot.name, intermediate_spot.name,
                "keeps the intermediate name w/ an outdated etag")
            self.assertEquals(
                updated_spot.capacity, intermediate_spot.capacity,
                "keeps the intermediate capacity w/ an outdate etag")
    def test_valid_json_outdated_etag(self):
        dummy_cache = cache.get_cache("django.core.cache.backends.dummy.DummyCache")
        with patch.object(models, "cache", dummy_cache):
            c = Client()
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 30

            response = c.get(self.url)
            etag = response["ETag"]

            intermediate_spot = Spot.objects.get(pk=self.spot.pk)
            intermediate_spot.name = "This interferes w/ the PUT"
            intermediate_spot.save()

            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag,
            )
            self.assertEquals(response.status_code, 409, "An outdated etag leads to a conflict")

            updated_spot = Spot.objects.get(pk=self.spot.pk)
            self.assertEquals(
                updated_spot.name, intermediate_spot.name, "keeps the intermediate name w/ an outdated etag"
            )
            self.assertEquals(
                updated_spot.capacity, intermediate_spot.capacity, "keeps the intermediate capacity w/ an outdate etag"
            )
Exemple #32
0
    def test_put_trusted_client_no_user(self):
        dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            consumer_name = "Trusted test consumer"

            key = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()
            secret = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()

            create_consumer = Consumer.objects.create(name=consumer_name, key=key, secret=secret)
            trusted_consumer = TrustedOAuthClient.objects.create(consumer=create_consumer, is_trusted=True)

            consumer = oauth2.Consumer(key=key, secret=secret)

            req = oauth2.Request.from_consumer_and_token(consumer, None, http_method='GET', http_url="http://testserver/api/v1/spot/%s" % self.spot.pk)

            oauth_header = req.to_header()
            c = Client()

            response = c.get(self.url, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            etag = response["ETag"]

            spot_dict = json.loads(response.content)
            spot_dict['name'] = "Failing to modify oauth"

            response = c.put(self.url, json.dumps(spot_dict), content_type="application/json", If_Match=etag, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            self.assertEquals(response.status_code, 401, "Rejects a PUT from a trusted oauth client w/o a given user")
Exemple #33
0
    def api_call(self, method, url, params={}):
        import json
        from django.test.client import Client
        c = Client()
        if method not in ('get', 'post', 'patch', 'delete', 'put'):
            return json.loads(dict(code=-1, msg='method is invalid'))
        if method == 'get':
            response_content = c.get(url, data=params, **self.headers).content
        elif method == 'post':
            response_content = c.post(url,
                                      data=json.dumps(params),
                                      content_type='application/json',
                                      **self.headers).content
        elif method == 'patch':
            response_content = c.patch(url,
                                       data=json.dumps(params),
                                       content_type='application/json',
                                       **self.headers).content
        elif method == 'delete':
            response_content = c.delete(url,
                                        data=json.dumps(params),
                                        content_type='application/json',
                                        **self.headers).content
        elif method == 'put':
            response_content = c.put(url,
                                     data=json.dumps(params),
                                     content_type='application/json',
                                     **self.headers).content
        response_content_dict = json.loads(
            str(response_content, encoding='utf-8'))

        return response_content_dict
Exemple #34
0
 def test_bad_json(self):
     c = Client()
     response = c.put(self.url,
                      'this is just text',
                      content_type="application/json",
                      If_Match=self.spot.etag)
     self.assertEquals(response.status_code, 400, "Rejects non-json")
Exemple #35
0
 def test_parse_validation_pass_extra(self):
     client = Client()
     response = client.put(
         '/simple/valid?format=json',
         '{"name": "Luke", "extra": "data"}',
         'application/json')
     self.assertEquals(response.status_code, 400)
Exemple #36
0
 def test_post_empty_data(self):
     client = Client()
     response = client.put(
         '/simple/mapper/dict/',
         '',
         'application/json')
     self.assertEquals(response.status_code, 200)
Exemple #37
0
    def test_valid_different_image_type_valid_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            with self.settings(MEDIA_ROOT=self.TEMP_DIR):
                c = Client()
                response = c.get(self.gif_url)
                etag = response["etag"]

                f = open("%s/../resources/test_png.png" % TEST_ROOT)
                f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT)

                new_name = "testing PUT name: {0}".format(random.random())

                response = c.put(self.gif_url, {
                    "description": new_name,
                    "image": f
                },
                                 If_Match=etag)
                self.assertEquals(response.status_code, 200)
                self.assertEquals(int(response["content-length"]),
                                  os.fstat(f.fileno()).st_size,
                                  "Loaded the new image")
                self.assertNotEqual(int(response["content-length"]),
                                    os.fstat(f2.fileno()).st_size,
                                    "Size doesn't match the original image")
                self.assertEquals(response["content-type"], "image/png",
                                  "Has the right content type")

                # Just to be sure
                response = c.get(self.gif_url)
                self.assertEquals(response["content-type"], "image/png",
                                  "Has the right content type")
Exemple #38
0
 def test_parse_validation_fail(self):
     client = Client()
     response = client.put(
         '/simple/valid?format=json',
         '{"name": "Luke Skywalker"}',
         'application/json')
     self.assertEquals(response.status_code, 400)
Exemple #39
0
    def test_valid_json_valid_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            user, created = User.objects.get_or_create(username='******')
            c = Client()
            c.login(username=user.username)
            new_name = "testing PUT name: {0}".format(random.random())
            new_capacity = 20

            response = c.get(self.url)
            etag = response["ETag"]

            response = c.put(
                self.url,
                '{"name":"%s","capacity":"%d", "location": {"latitude": 55, "longitude": 30} }'
                % (new_name, new_capacity),
                content_type="application/json",
                If_Match=etag)
            self.assertEquals(response.status_code, 200)

            updated_spot = Spot.objects.get(pk=self.spot.pk)
            self.assertEquals(updated_spot.name, new_name,
                              "a valid PUT changes the name")
            self.assertEquals(updated_spot.capacity, new_capacity,
                              "a valid PUT changes the capacity")
Exemple #40
0
class UploadFeedTest(unittest.TestCase):
    def setUp(self):
        # startup the client
        self.client = Client()

    def test_details(self):
        with open('/path/to/feed/file/vipFeed-00-2012-01-01.zip',
                  'rb') as feed:
            request = {
                'content_type': 'application/zip',
                'data': {
                    'filename': 'vipFeed-00-2012-01-01.zip',
                    'attachment': feed,
                },
                'extra': {
                    'HTTP_CONTENT_LENGTH': 3715219,
                    'HTTP_IF_MATCH': 'vipFeed-00-2012-01-01.zip'
                }
            }

            # issue a PUT request
            response = self.client.put("/api/feed/upload/", **request)

            # Check that the response is 200 OK
            self.assertEqual(response.status_code, 200)
Exemple #41
0
    def test_complex_xml(self):
        xml = """
        <root>
          <a>3.99</a>
          <b>text</b>
          <c>
            <c_item>1</c_item>
            <c_item>2</c_item>
            <c_item>3.99</c_item>
          </c>
          <d>
            <d_item>
              <age>23</age>
              <name>luke</name>
            </d_item>
            <d_item>
              <age>65</age>
              <name>obi</name>
            </d_item>
          </d>
        </root>
        """

        client = Client()
        response = client.put('/simple/mapper/echo', xml, 'text/xml')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(testurls.echoresource.mydata, {
            'a': 3.99,
            'b': 'text',
            'c': [1, 2, 3.99],
            'd': [{'age': 23, 'name': 'luke'}, {'age': 65, 'name': 'obi'}]
            })
        response = client.get('/simple/mapper/echo', **{'HTTP_ACCEPT': 'text/xml'})
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.content, '<?xml version="1.0" encoding="utf-8"?>\n<root><a>3.99</a><c><c_item>1</c_item><c_item>2</c_item><c_item>3.99</c_item></c><b>text</b><d><d_item><age>23</age><name>luke</name></d_item><d_item><age>65</age><name>obi</name></d_item></d></root>')
Exemple #42
0
    def test_hours(self):
        dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            spot = Spot.objects.create(name="This spot has available hours")
            etag = spot.etag

            put_obj = {
                'name': "This spot has available hours",
                'capacity': "4",
                'location': {
                    'latitude': '55',
                    'longitude': '30',
                },
                'available_hours': {
                    'monday': [["00:00", "10:00"], ["11:00", "14:00"]],
                    'tuesday': [["11:00", "14:00"]],
                    'wednesday': [["11:00", "14:00"]],
                    'thursday': [["11:00", "14:00"]],
                    'friday': [["11:00", "14:00"]],
                    'saturday': [],
                    'sunday': [["11:00", "14:00"]],
                }
            }

            c = Client()
            url = "/api/v1/spot/%s" % spot.pk
            response = c.put(url, json.dumps(put_obj), content_type="application/json", If_Match=etag)
            spot_dict = json.loads(response.content)

            self.maxDiff = None
            self.assertEquals(spot_dict["available_hours"], put_obj["available_hours"], "Data from the web service matches the data for the spot")
Exemple #43
0
    def test_customer_crud(self):
        c = Client()

        customer = {'name': 'My First Customer'}

        response = c.post(reverse('customer:api:customers:list'), customer)
        self.assertEqual(201, response.status_code)  # HTTP Created
        self.assertIn('Location', response)
        location = response['Location']

        response = c.get(location)
        self.assertEqual(200, response.status_code)  # HTTP OK

        content = simplejson.loads(response.content)
        self.assertEqual(customer['name'], content['name'])
        self.assertEqual(location, content['url'])
        self.assertIn('phone_numbers', content)

        customer['name'] = 'John Doe'
        response = c.put(location, customer)
        self.assertEqual(200, response.status_code)  # HTTP OK
        content = simplejson.loads(response.content)
        self.assertEqual(customer['name'], content['name'])
        self.assertEqual(location, content['url'])
        self.assertIn('phone_numbers', content)

        response = c.delete(location)
        self.assertEqual(204, response.status_code)  # HTTP No Content

        response = c.get(location)
        self.assertEqual(404, response.status_code)  # HTTP Not Found
Exemple #44
0
    def test_invalid_image_type_valid_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            with self.settings(MEDIA_ROOT=self.TEMP_DIR):
                c = Client()
                response = c.get(self.gif_url)
                etag = response["etag"]

                f = open("%s/../resources/test_png.png" % TEST_ROOT)
                f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT)

                new_name = "testing PUT name: {0}".format(random.random())

                c = Client()
                f = open("%s/../resources/fake_jpeg.jpg" % TEST_ROOT)
                response = c.put(self.gif_url, {
                    "description": "This is really a text file",
                    "image": f
                },
                                 If_Match=etag)
                f.close()

                self.assertEquals(
                    response.status_code, 400,
                    "Gives a Bad Request in response to a non-image")
Exemple #45
0
 def test_invalid_id_too_high(self):
     with self.settings(MEDIA_ROOT=self.TEMP_DIR):
         c = Client()
         test_id = self.gif.pk + 10000
         test_url = "%s/image/%s" % (self.url, test_id)
         response = c.put(test_url, '{}', content_type="application/json")
         self.assertEquals(response.status_code, 404)
Exemple #46
0
    def test_valid_different_image_type_valid_etag(self):
        with self.settings(MEDIA_ROOT=self.TEMP_DIR):
            c = Client()
            response = c.get(self.gif_url)

            etag = response["etag"]

            f = open("%s/../resources/test_png.png" % TEST_ROOT)
            f2 = open("%s/../resources/test_gif.gif" % TEST_ROOT)

            new_name = "testing PUT name: {0}".format(random.random())

            response = c.put(self.gif_url,
                             files={
                                 "description": new_name,
                                 "image": f
                             },
                             content_type="multipart/form-data; "
                             "boundary=--aklsjf--",
                             If_Match=etag)
            self.assertEquals(response.status_code, 200)
            f = open("%s/../resources/test_png.png" % TEST_ROOT)

            # Just to be sure
            response = c.get(self.gif_url)
            self.assertEquals(response["content-type"], "image/png")
            self.assertEquals(int(response["content-length"]), len(f.read()))
            self.assertNotEqual(int(response["content-length"]),
                                len(f2.read()))
Exemple #47
0
    def test_maps_search(self):
        """Test maps search can function properly
        """
        # first create two maps
        c = Client()

        # Test successful new map creation
        c.login(username=self.user, password=self.passwd)

        new_map = reverse('new_map_json')
        response = c.post(new_map, data=self.viewer_config,content_type="text/json")
        self.assertEquals(response.status_code,200)
        map_id = int(json.loads(response.content)['id'])
        response = c.post(new_map, data=self.viewer_config_alternative,content_type="text/json")
        self.assertEquals(response.status_code,200)
        map_id_2 = int(json.loads(response.content)['id'])
        c.logout()

        url = reverse('maps_search_api') + '?'

        # Test GET method
        response = c.get(url, {'q': '', 'start': 1}, content_type="text/json")
        self.assertEquals(response.status_code,200)
        response_dict = json.loads(response.content)
        self.assertEquals(response_dict['success'], True)

        # Test POST method
        response = c.post(url, {'q': '', 'start': 1}, content_type="text/json")
        self.assertEquals(response.status_code,200)
        response_dict = json.loads(response.content)
        self.assertEquals(response_dict['success'], True)

        # Test methods other than GET or POST
        response = c.put(url)
        self.assertEquals(response.status_code,405)
Exemple #48
0
    def test_docstring_example(self):
        """ if list item names are same all the time we not know the order """

        xml = """
        <root>
            <orders>
              <order_item><id>3</id><name>Skates</name></order_item>
              <order_item><id>4</id><name>Snowboard</name></order_item>
              <order_info>Urgent</order_info>
            </orders>
        </root>
        """

        client = Client()
        response = client.put('/simple/mapper/echo', xml, 'text/xml')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(
            testurls.echoresource.mydata, {
                'orders': [{
                    'id': 3,
                    'name': 'Skates'
                }, {
                    'id': 4,
                    'name': 'Snowboard'
                }, 'Urgent']
            })
Exemple #49
0
    def test_update_capability(self):
        """
        Tests updating the capability through the API.
        """

        if not self.response_capability_enabled:
            return

        capability = Staffing.objects.create(firestation=self.fire_station, firefighter=1, firefighter_emt=1,
                          firefighter_paramedic=1, ems_emt=1, ems_paramedic=1, officer=1, officer_paramedic=1,
                          ems_supervisor=1, chief_officer=1)

        url = '{0}{1}/?format=json'.format(reverse('api_dispatch_list',
                                                   args=[self.current_api_version, 'capabilities']), capability.id)

        c = Client()
        c.login(**{'username': '******', 'password': '******'})

        params = dict(firefighter=2, firefighter_emt=2, firefighter_paramedic=2, ems_emt=2, ems_paramedic=2, officer=2,
                      officer_paramedic=2, ems_supervisor=2, chief_officer=2)

        response = c.put(url, data=json.dumps(params), content_type='application/json')
        self.assertEqual(response.status_code, 204)

        updated_capability = Staffing.objects.get(id=capability.id)
        self.assertEqual(updated_capability.firefighter, 2)
        self.assertEqual(updated_capability.firefighter_emt, 2)
        self.assertEqual(updated_capability.firefighter_paramedic, 2)
        self.assertEqual(updated_capability.ems_emt, 2)
        self.assertEqual(updated_capability.ems_paramedic, 2)
        self.assertEqual(updated_capability.officer, 2)
        self.assertEqual(updated_capability.officer_paramedic, 2)
        self.assertEqual(updated_capability.ems_supervisor, 2)
        self.assertEqual(updated_capability.chief_officer, 2)
Exemple #50
0
class replyCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_reply_detail(self):
        put = { 'content'   :   "test",
                'status'    :   1,
               }

        response = self.client.put("/status/reply/crud/", json.dumps(put), "text")
        reply = StatusReply.objects.filter(content="test")[0]
        self.assertEqual(reply.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/status/reply/crud/%d" % reply.pk, json.dumps(post), "text")
        reply = StatusReply.objects.filter(content="test2")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(reply.content, "test2")
        
        response = self.client.get("/status/reply/crud/%d" % reply.pk)
        r = json.loads(response.content)[0]
        self.assertEqual("test2", r["fields"]["content"])
        
        response = self.client.delete("/status/reply/crud/%d" % reply.pk)
        reply = StatusReply.objects.filter(content="test2")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(reply))
Exemple #51
0
    def test_put_untrusted_oauth(self):
        with self.settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.oauth',
                           SPOTSEEKER_SPOT_FORM='spotseeker_server.default_forms.spot.DefaultSpotForm'):
            consumer_name = "Untrusted test consumer"

            key = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()
            secret = hashlib.sha1("{0} - {1}".format(random.random(), time.time())).hexdigest()

            create_consumer = Consumer.objects.create(name=consumer_name, key=key, secret=secret)

            consumer = oauth2.Consumer(key=key, secret=secret)

            req = oauth2.Request.from_consumer_and_token(consumer, None, http_method='GET', http_url="http://testserver/api/v1/spot/%s" % self.spot.pk)

            oauth_header = req.to_header()
            c = Client()

            response = c.get(self.url, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            etag = response["ETag"]

            spot_dict = json.loads(response.content)
            spot_dict['name'] = "Failing to modify oauth"
            spot_dict['location'] = {"latitude": 55, "longitude": -30}

            response = c.put(self.url, json.dumps(spot_dict), content_type="application/json", If_Match=etag, HTTP_AUTHORIZATION=oauth_header['Authorization'])
            self.assertEquals(response.status_code, 401, "Rejects a PUT from a non-trusted oauth client")
    def test_update_activity_stop_time_put_request(self):
        self.create_activity()
        client = Client()
        client.login(username='******', password='******')

        response = client.put(reverse('update_activity_end_time', kwargs={'activity_id':1,'year': 2018,'month':3,'day':28, 'hr':13, 'minute':25,'sec':25}))
        self.assertEqual(response.status_code, 200)
Exemple #53
0
class HttpMethodTest(TestCase):
    fixtures = ['gitspatial/fixtures/test_data.json']

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

    def test_get(self):
        response = self.client.get(
            '/api/v1/JasonSanford/mecklenburg-gis-opendata/data/polling_locations.geojson'
        )
        self.assertEqual(response.status_code, 200)

    def test_put(self):
        response = self.client.put(
            '/api/v1/JasonSanford/mecklenburg-gis-opendata/data/polling_locations.geojson'
        )
        self.assertEqual(response.status_code, 405)

    def test_post(self):
        response = self.client.post(
            '/api/v1/JasonSanford/mecklenburg-gis-opendata/data/polling_locations.geojson'
        )
        self.assertEqual(response.status_code, 405)

    def test_delete(self):
        response = self.client.delete(
            '/api/v1/JasonSanford/mecklenburg-gis-opendata/data/polling_locations.geojson'
        )
        self.assertEqual(response.status_code, 405)
Exemple #54
0
class scheduleCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_rent_detail(self):
        put = { 'content'   :   "test",
                'starttime' : '2009-1-1',
                'endtime': '2010-1-1',
               }
        
        response = self.client.put("/schedule/crud/", json.dumps(put), "text")
        schedule = Schedule.objects.get(pk=int(response.content))
        self.assertEqual(schedule.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/schedule/crud/%d" % schedule.pk, json.dumps(post), "text")
        schedule = Schedule.objects.get(pk=schedule.pk)
        self.assertEqual(response.content, '"success"')
        self.assertEqual(schedule.content, "test2")
        
        
        response = self.client.get("/schedule/crud/%d" % schedule.pk)
        a = json.loads(response.content)[0]
        self.assertEqual("test2", a["fields"]["content"])
        
        i = schedule.pk
        response = self.client.delete("/schedule/crud/%d" % i)
        rents = Schedule.objects.filter(pk=i)
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(rents))
Exemple #55
0
    def test_no_number_conversion(self):
        """ test that numbers are left as strings """

        xml = """
        <root>
          <a>
            <hiihoo>1</hiihoo>
            <hiihoo>2.99</hiihoo>
            <hiihoo>text</hiihoo>
          </a>
        </root>
        """

        datamapper.manager.register_mapper(XmlMapper(), 'text/xml', 'xml')
        client = Client()
        response = client.put('/simple/mapper/echo', xml, 'text/xml')
        self.assertEquals(response.status_code, 200)
        self.assertTrue(
            testurls.echoresource.mydata == {'a': ['1', '2.99', 'text']})
        response = client.get('/simple/mapper/echo.xml')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(
            response.content,
            '<?xml version="1.0" encoding="utf-8"?>\n<root><a><a_item>1</a_item><a_item>2.99</a_item><a_item>text</a_item></a></root>'
        )
        datamapper.manager.register_mapper(XmlMapper(numbermode='basic'),
                                           'text/xml', 'xml')
Exemple #56
0
    def test_basic_oks(self):
        spot = Spot.objects.create(name="This is for testing Sharing 1")

        user, create = User.objects.get_or_create(username='******')

        c = Client()
        c.login(username='******')
        url = "/api/v1/spot/%s/share" % (spot.pk)

        json_data = {
            "to": "*****@*****.**",
            "comment": "This is a sweet space",
            "from": "*****@*****.**",
        }

        response = c.put(url,
                         json.dumps(json_data),
                         content_type="application/json",
                         TESTING_OAUTH_USER="******")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "true", "yup, sent")

        self.assertEqual(mail.outbox[0].to[0], '*****@*****.**',
                         'right to')
        mail.outbox = []
Exemple #57
0
 def test_parse_validation_pass(self):
     client = Client()
     response = client.put('/simple/valid?format=json', '{"name": "Luke"}',
                           'application/json')
     self.assertEquals(response.status_code, 200)
     self.assertEquals(response['Content-Type'],
                       'application/json; charset=utf-8')
     self.assertEquals(response.content, '')
Exemple #58
0
    def test_bad_url(self):
        with self.settings(MEDIA_ROOT=self.TEMP_DIR):
            c = Client()
            item = Item.objects.create(name="This is the wrong Item")

            url = "/api/v1/item/{0}/image/{1}".format(item.pk, self.jpeg.pk)
            response = c.put(url, '{}', content_type="application/json")
            self.assertEquals(response.status_code, 404)