Ejemplo n.º 1
0
class VipRequestDeleteTestCase(NetworkApiTestCase):
    def setUp(self):
        self.client = Client()

    def tearDown(self):
        pass

    def test_delete_one_ip_use_vips_success(self):
        """Test of success to delete two vips."""

        # Does delete request
        response = self.client.delete(
            '/api/v3/vip-request/1/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)

    def test_delete_one_vips_success(self):
        """Test of success to delete two vips."""

        # Does delete request
        response = self.client.delete(
            '/api/v3/vip-request/2/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)
Ejemplo n.º 2
0
    def test_actual_delete_with_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()
            response = c.get(self.url)
            etag = response["ETag"]
            response = c.delete(self.url, If_Match=etag)

            self.assertEquals(response.status_code, 200,
                              "Gives a GONE in response to a valid delete")

            response = c.get(self.url)
            self.assertEquals(response.status_code, 404,
                              "Gives a 404 on GET after a delete")

            response = c.delete(self.url)
            self.assertEquals(response.status_code, 404,
                              "Gives a 404 on DELETE after a delete")

            try:
                test_spot = Spot.objects.get(pk=self.spot.pk)
            except Exception as e:
                test_spot = None

            self.assertIsNone(test_spot, "Can't objects.get a deleted spot")
Ejemplo n.º 3
0
    def test_actual_delete_no_etag(self):
        dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()

            #GIF
            response = c.delete(self.gif_url)
            self.assertEquals(response.status_code, 409, "Deleting w/o an etag is a conflict")

            response = c.get(self.gif_url)
            self.assertEquals(response.status_code, 200, "Resource still exists after DELETE w/o an etag")

            #JPEG
            response = c.delete(self.jpeg_url)
            self.assertEquals(response.status_code, 409, "Deleting w/o an etag is a conflict")

            response = c.get(self.jpeg_url)
            self.assertEquals(response.status_code, 200, "Resource still exists after DELETE w/o an etag")

            #PNG
            response = c.delete(self.png_url)
            self.assertEquals(response.status_code, 409, "Deleting w/o an etag is a conflict")

            response = c.get(self.png_url)
            self.assertEquals(response.status_code, 200, "Resource still exists after DELETE w/o an etag")
Ejemplo n.º 4
0
    def test_actual_delete_no_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()

            # GIF
            response = c.delete(self.gif_url)

            self.assertEquals(response.status_code, 200)

            response = c.get(self.gif_url)
            self.assertEquals(response.status_code, 404)

            # JPEG
            response = c.delete(self.jpeg_url)
            self.assertEquals(response.status_code, 200)

            response = c.get(self.jpeg_url)
            self.assertEquals(response.status_code, 404)

            # PNG
            response = c.delete(self.png_url)
            self.assertEquals(response.status_code, 200)

            response = c.get(self.png_url)
            self.assertEquals(response.status_code, 404)
Ejemplo n.º 5
0
class DeletePollTests(TestCase):
    def setUp(self):
        self.client = Client()
        create_poll(question="question1", days=-5, vtype=1)
        poll = Poll.objects.create(
            question="question2",
            pub_date=timezone.now() + datetime.timedelta(days=-10),
            user=User.objects.get(username="******"),
            vtype=2,
            close_date=None,
        )

        for _ in range(2):
            create_ballot(poll)
        self.client.login(username='******', password='******')

    def test_delete_one_poll(self):
        self.client.delete('/approval_polls/1/', follow=True)
        response = self.client.get(reverse('approval_polls:my_polls'))
        self.assertEqual(response.status_code, 200)
        self.assertQuerysetEqual(response.context['latest_poll_list'],
                                 ['<Poll: question2>'])
        response = self.client.get('/approval_polls/1/')
        self.assertEqual(response.status_code, 404)

    def test_delete_all_polls(self):
        self.client.delete('/approval_polls/1/', follow=True)
        self.client.delete('/approval_polls/2/', follow=True)
        response = self.client.get(reverse('approval_polls:my_polls'))
        self.assertEqual(response.status_code, 200)
        self.assertQuerysetEqual(response.context['latest_poll_list'], [])
        response = self.client.get('/approval_polls/1/')
        self.assertEqual(response.status_code, 404)
        response = self.client.get('/approval_polls/2/')
        self.assertEqual(response.status_code, 404)
Ejemplo n.º 6
0
    def test_actual_delete_no_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()

            #GIF
            response = c.delete(self.gif_url)
            self.assertEquals(response.status_code, 400,
                              "Deleting w/o an etag is a bad request")

            response = c.get(self.gif_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")

            #JPEG
            response = c.delete(self.jpeg_url)
            self.assertEquals(response.status_code, 400,
                              "Deleting w/o an etag is a bad request")

            response = c.get(self.jpeg_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")

            #PNG
            response = c.delete(self.png_url)
            self.assertEquals(response.status_code, 400,
                              "Deleting w/o an etag is a bad request")

            response = c.get(self.png_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")
Ejemplo n.º 7
0
    def test_actual_delete_no_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()

            # GIF
            response = c.delete(self.gif_url)

            self.assertEquals(response.status_code, 200)

            response = c.get(self.gif_url)
            self.assertEquals(response.status_code, 404)

            # JPEG
            response = c.delete(self.jpeg_url)
            self.assertEquals(response.status_code, 200)

            response = c.get(self.jpeg_url)
            self.assertEquals(response.status_code, 404)

            # PNG
            response = c.delete(self.png_url)
            self.assertEquals(response.status_code, 200)

            response = c.get(self.png_url)
            self.assertEquals(response.status_code, 404)
Ejemplo n.º 8
0
class EnvironmentVipDeleteTestCase(NetworkApiTestCase):

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/api_ogp/fixtures/initial_objecttype.json',
        'networkapi/api_ogp/fixtures/initial_objectgrouppermissiongeneral.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/requisicaovips/fixtures/initial_optionsvip.json',
        'networkapi/api_environment_vip/fixtures/initial_base.json',
    ]

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

    def tearDown(self):
        pass

    def test_delete_one_env_success(self):
        """Test of success to delete of one environment vip."""

        response = self.client.delete(
            '/api/v3/environment-vip/1/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)

        response = self.client.get(
            '/api/v3/environment-vip/1/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(404, response.status_code)

    def test_delete_one_env_inexistent_error(self):
        """Test of success to delete of one environment vip."""

        response = self.client.delete(
            '/api/v3/environment-vip/1000/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(404, response.status_code)

    def test_delete_one_env_related_network_error(self):
        """Test of error to delete one environment vip related with network
        ipv4.
        """

        response = self.client.delete(
            '/api/v3/environment-vip/2/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(400, response.status_code)
Ejemplo n.º 9
0
class WebClientTestCase(TestCase):
    def setUp(self):
        self.c = Client()

    def test_one(self, user='******', topic='economy'):

        url_topic_user = "******" % (topic, user)
        url_topic = '/' + topic + '/'

        r = self.c.get('/zzz')
        self.assertEqual(r.status_code, 404, msg=r.reason_phrase) # unspecied behavior, 404 would be ok

        r = self.c.get(url_topic_user)
        self.assertEqual(r.status_code, 204, msg=r.reason_phrase)

        r = self.c.post(url_topic_user)
        self.assertEqual(r.status_code, 201, msg=r.reason_phrase)

        r = self.c.post(url_topic_user)
        self.assertEqual(r.status_code, 201, msg=r.reason_phrase)

        r = self.c.get(url_topic_user)
        self.assertEqual(r.status_code, 204, msg=r.reason_phrase) # no subscription

        # publish a message
        json_str = json.dumps({"message": "MSFT goes up!"})
        r = self.c.post(url_topic, data=json_str, content_type='application/json',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
            )
        self.assertEqual(r.status_code, 201, msg=r.reason_phrase)

        # first time we need to get one message for john
        r = self.c.get(url_topic_user)
        self.assertEqual(r.status_code, 200, msg=r.reason_phrase)

        # 2nd time we need to get no messages for john (204 code)
        r = self.c.get(url_topic_user)
        self.assertEqual(r.status_code, 204, msg=r.reason_phrase)

        # unsubcribe user from topic
        r = self.c.delete(url_topic_user)
        self.assertEqual(r.status_code, 200, msg=r.reason_phrase)

        # re-unsubcribe user from topic (should get 404)
        r = self.c.delete(url_topic_user)
        self.assertEqual(r.status_code, 404, msg=r.reason_phrase)

        # publish a new message
        json_str = json.dumps({"message": "APPL goes down!"})
        r = self.c.post(url_topic, data=json_str, content_type='application/json',
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
            )
        self.assertEqual(r.status_code, 201, msg=r.reason_phrase)

        # now we should NOT get this message for john because he unsubscribed
        r = self.c.get(url_topic_user)
        self.assertEqual(r.status_code, 204, msg=r.reason_phrase)
Ejemplo n.º 10
0
    def test_actual_delete_expired_etag(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            c = Client()

            #GIF
            response = c.get(self.gif_url)
            etag = response["ETag"]

            intermediate_img = SpotImage.objects.get(pk=self.gif.pk)
            intermediate_img.name = "This interferes w/ the DELETE"
            intermediate_img.save()

            response = c.delete(self.gif_url, If_Match=etag)
            self.assertEquals(response.status_code, 409,
                              "Deleting w an outdated etag is a conflict")

            response = c.get(self.gif_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")

            #JPEG
            response = c.get(self.jpeg_url)
            etag = response["ETag"]

            intermediate_img = SpotImage.objects.get(pk=self.jpeg.pk)
            intermediate_img.name = "This interferes w/ the DELETE"
            intermediate_img.save()

            response = c.delete(self.jpeg_url, If_Match=etag)
            self.assertEquals(response.status_code, 409,
                              "Deleting w an outdated etag is a conflict")

            response = c.get(self.jpeg_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")

            #PNG
            response = c.get(self.png_url)
            etag = response["ETag"]

            intermediate_img = SpotImage.objects.get(pk=self.png.pk)
            intermediate_img.name = "This interferes w/ the DELETE"
            intermediate_img.save()

            response = c.delete(self.png_url, If_Match=etag)
            self.assertEquals(response.status_code, 409,
                              "Deleting w an outdated etag is a conflict")

            response = c.get(self.png_url)
            self.assertEquals(
                response.status_code, 200,
                "Resource still exists after DELETE w/o an etag")
Ejemplo n.º 11
0
class NeighborV6DeleteErrorTestCase(NetworkApiTestCase):

    neighbor_v6_uri = '/api/v4/neighborv6/'
    fixtures_path = 'networkapi/api_neighbor/v4/fixtures/neighbor_v6/{}'

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/api_ogp/fixtures/initial_objecttype.json',
        'networkapi/api_ogp/fixtures/initial_objectgrouppermissiongeneral.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        fixtures_path.format('initial_vrf.json'),
        fixtures_path.format('initial_environment.json'),
        fixtures_path.format('initial_vlan.json'),
        fixtures_path.format('initial_networkipv6.json'),
        fixtures_path.format('initial_ipv6.json'),
        fixtures_path.format('initial_asn.json'),
        fixtures_path.format('initial_neighbor_v6.json')
    ]

    def setUp(self):
        self.client = Client()
        self.authorization = self.get_http_authorization('test')

    def tearDown(self):
        pass

    def test_delete_inexistent_neighbors_v6(self):
        """Test DELETE inexistent NeighborsV6."""

        delete_ids = [1000, 1001]
        uri = mount_url(self.neighbor_v6_uri, delete_ids)

        response = self.client.delete(uri,
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(404, response.status_code)
        self.compare_values(u'NeighborV6 id = 1000 do not exist',
                            response.data['detail'])

    def test_delete_deployed_neighbor_v6(self):
        """Test DELETE deployed NeighborV6."""

        delete_ids = [2]
        uri = mount_url(self.neighbor_v6_uri, delete_ids)

        response = self.client.delete(uri,
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(400, response.status_code)
        self.compare_values(u'NeighborV6 id = 2 is deployed',
                            response.data['detail'])
Ejemplo n.º 12
0
class NeighborDeleteSuccessTestCase(NetworkApiTestCase):
    """Class for Test Neighbor package Success DELETE cases."""

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/api_neighbor/v4/fixtures/initial_vrf.json',
        'networkapi/api_neighbor/v4/fixtures/initial_virtual_interface.json',
        'networkapi/api_neighbor/v4/fixtures/initial_neighbor.json',
    ]

    def setUp(self):
        self.client = Client()
        self.authorization = self.get_http_authorization('test')

    def tearDown(self):
        pass

    def test_delete_one_neighbor(self):
        """Success Test of DELETE one Neighbor."""

        response = self.client.delete('/api/v4/neighbor/1/',
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(200, response.status_code)

        response = self.client.get('/api/v4/neighbor/1/',
                                   HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(404, response.status_code)

        self.compare_values(u'Neighbor 1 do not exist.',
                            response.data['detail'])

    def test_delete_two_neighbor(self):
        """Success Test of DELETE two Neighbor."""

        response = self.client.delete('/api/v4/neighbor/1;2/',
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(200, response.status_code)

        for id_ in xrange(1, 2 + 1):
            response = self.client.get('/api/v4/neighbor/%s/' % id_,
                                       HTTP_AUTHORIZATION=self.authorization)

            self.compare_status(404, response.status_code)

            self.compare_values(u'Neighbor %s do not exist.' % id_,
                                response.data['detail'])
Ejemplo n.º 13
0
class AsDeleteSuccessTestCase(NetworkApiTestCase):
    """Class for Test AS package Success DELETE cases."""

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/api_as/v4/fixtures/initial_as.json',
        'networkapi/api_as/v4/fixtures/initial_equipment.json',
        'networkapi/api_as/v4/fixtures/initial_asequipment.json'
    ]

    def setUp(self):
        self.client = Client()
        self.authorization = self.get_http_authorization('test')

    def tearDown(self):
        pass

    def test_delete_one_as(self):
        """Success Test of DELETE one AS."""

        response = self.client.delete('/api/v4/as/3/',
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(200, response.status_code)

        response = self.client.get('/api/v4/as/3/',
                                   HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(404, response.status_code)

        self.compare_values(u'AS 3 do not exist.', response.data['detail'])

    def test_delete_two_as(self):
        """Success Test of DELETE two AS."""

        response = self.client.delete('/api/v4/as/3;4/',
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(200, response.status_code)

        for id_ in xrange(3, 4 + 1):
            response = self.client.get('/api/v4/as/%s/' % id_,
                                       HTTP_AUTHORIZATION=self.authorization)

            self.compare_status(404, response.status_code)

            self.compare_values(u'AS %s do not exist.' % id_,
                                response.data['detail'])
Ejemplo n.º 14
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()
Ejemplo n.º 15
0
class TestProcessingConfigurationAPI(TestCase):
    fixture_files = ['test_user.json']
    fixtures = [os.path.join(THIS_DIR, 'fixtures', p) for p in fixture_files]

    def setUp(self):
        self.client = Client()
        self.client.login(username='******', password='******')
        helpers.set_setting('dashboard_uuid', 'test-uuid')
        settings.SHARED_DIRECTORY = tempfile.gettempdir()
        self.config_path = os.path.join(
            settings.SHARED_DIRECTORY,
            'sharedMicroServiceTasksConfigs/processingMCPConfigs/')
        if not os.path.exists(self.config_path):
            os.makedirs(self.config_path)
        install_builtin_config('default')

    def test_get_existing_processing_config(self):
        response = self.client.get(reverse('processing_configuration',
                                           args=['default']),
                                   HTTP_ACCEPT='xml')
        assert response.status_code == 200
        assert etree.fromstring(
            response.content).xpath('.//preconfiguredChoice')

    def test_delete_and_regenerate(self):
        response = self.client.delete(
            reverse('processing_configuration', args=['default']), )
        assert response.status_code == 200
        assert not os.path.exists(
            os.path.join(self.config_path, 'defaultProcessingMCP.xml'))

        response = self.client.get(reverse('processing_configuration',
                                           args=['default']),
                                   HTTP_ACCEPT='xml')
        assert response.status_code == 200
        assert etree.fromstring(
            response.content).xpath('.//preconfiguredChoice')
        assert os.path.exists(
            os.path.join(self.config_path, 'defaultProcessingMCP.xml'))

    def test_404_for_non_existent_config(self):
        response = self.client.get(reverse('processing_configuration',
                                           args=['nonexistent']),
                                   HTTP_ACCEPT='xml')
        assert response.status_code == 404

    def test_404_for_delete_non_existent_config(self):
        response = self.client.delete(
            reverse('processing_configuration', args=['nonexistent']), )
        assert response.status_code == 404
Ejemplo n.º 16
0
 def test_roverlay_ro_delete(self):
     """
     Test logic for deleting RO aggregation by DELETE to service
     """
     self.assertEqual(len(ResearchObject.objects.all()), 0)
     self.assertEqual(len(AggregatedResource.objects.all()), 0)
     c = Client()
     # Create new RO
     base_uri = "http://example.org/resource/"
     uri_list = (
         [ "# Comment at start of URI list"
         , base_uri+"res1"
         , base_uri+"res2"
         , base_uri+"res3"
         ])
     uri_text = "\n".join(uri_list)
     r = c.post("/rovserver/", data=uri_text, content_type="text/uri-list")
     self.assertEqual(r.status_code, 201)
     ro_uri = r["Location"]
     self.assertEqual(len(ResearchObject.objects.all()), 1)
     self.assertEqual(len(AggregatedResource.objects.all()), 3)
     # Delete RO
     r = c.delete(ro_uri)
     self.assertEqual(r.status_code, 204)
     # Check RO and aggregated content are gone
     ros = ResearchObject.objects.filter(uri=ro_uri)
     self.assertEqual(len(ros), 0)
     ars = AggregatedResource.objects.all()
     self.assertEqual(len(ars), 0)
     return
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
class SimpleTest(TestCase):
    def setUp(self):
        self.client = Client()

    def canPostAndRetrieveMessage(self):
        textToPost = 'a fun text message to Gleet!'

        response = self.client.post("/messages", {'message': textToPost})
        self.assertEqual(200, response.status_code)
        message = list(serializers.deserialize("json", response.content))[0]
        self.assertEqual(textToPost, message.object.message)

        response = self.client.get("/messages")
        deserializedMessage = None
        messages = serializers.deserialize("json", response.content)
        for message in messages:
            deserializedMessage = message.object
            self.assertEqual(textToPost, deserializedMessage.message)
            self.assertNotEqual(None, deserializedMessage.timestamp)

        response = self.client.delete("/messages/" +
                                      str(deserializedMessage.id))
        self.assertEqual(200, response.status_code)

        messages = serializers.deserialize(
            "json",
            self.client.get("/messages").content)
        self.assertEqual(0, len(list(messages)))

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

        self.assertEqual(200, response.status_code)
Ejemplo n.º 19
0
class ApiCollectionTest(unittest.TestCase):
    """ API Collection class unit tests
    """
    COL_PATH_URL = reverse('collection-api')

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

    def tearDown(self):
        del self.client

    @patch.object(DB, 'get_collection_names', return_value=['ids', 'requests'])
    def test_get_logs_collections_name(self, mock_request_dao):
        """ Testing getting all collection names in database
        """
        ret = self.client.get(ApiCollectionTest.COL_PATH_URL)
        mock_request_dao.assert_called_once_with()
        self.assertIsNotNone(ret)
        self.assertEqual(ret.status_code, 200)
        self.assertEqual(ret.data, {'result': ['ids', 'requests']})

    @patch.object(RequestsDao, 'remove')
    def test_remove_log_collection_status_204(self, mock_request_dao):
        """ Testing calling remove collection in mongo
        """
        ret = self.client.delete(ApiCollectionTest.COL_PATH_URL)
        mock_request_dao.assert_called_once_with()
        self.assertIsNotNone(ret)
        self.assertEqual(ret.status_code, 204,
                         "Correct remove status returned")
        self.assertEqual(ret.status_text, 'NO CONTENT')
Ejemplo n.º 20
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)
Ejemplo n.º 21
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
 def test_delete_post(self):
     c = Client()
     response = c.delete('/author/posts/create_post', {'title': '1',
                                                       'description': 'aaaa',
                                                       'text_body': '1231',
                                                       'user': '******'})
     self.assertEqual(response.status_code, 301)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
Archivo: tests.py Proyecto: sheimi/oedu
class AnnouncementCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")

    def test_index(self):
        pass

    def test_anno_detail(self):
        put = {"title": "test", "content": "test", "grade": 2011}

        response = self.client.put("/anno/crud/", json.dumps(put), "text")
        self.assertEqual(response.content, "2")
        anno = Announcement.objects.filter(title="test")[0]
        self.assertEqual(anno.content, "test")

        post = {"content": "test2"}
        response = self.client.post("/anno/crud/%d" % anno.pk, json.dumps(post), "text")
        anno = Announcement.objects.filter(title="test")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(anno.content, "test2")

        response = self.client.get("/anno/crud/%d" % anno.pk)
        a = json.loads(response.content)[0]
        self.assertEqual("test", a["fields"]["title"])

        response = self.client.delete("/anno/crud/%d" % anno.pk)
        annos = Announcement.objects.filter(title="test")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(annos))
Ejemplo n.º 25
0
class NeighborDeleteErrorTestCase(NetworkApiTestCase):
    """Class for Test Neighbor package Error DELETE cases."""

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/api_neighbor/v4/fixtures/initial_vrf.json',
        'networkapi/api_neighbor/v4/fixtures/initial_virtual_interface.json',
        'networkapi/api_neighbor/v4/fixtures/initial_neighbor.json',
    ]

    def setUp(self):
        self.client = Client()
        self.authorization = self.get_http_authorization('test')

    def tearDown(self):
        pass

    def test_delete_one_inexistent_neighbor(self):
        """Error Test of DELETE one inexistent Neighbor."""

        delete_url = '/api/v4/neighbor/1000/'

        response = self.client.delete(delete_url,
                                      HTTP_AUTHORIZATION=self.authorization)

        self.compare_status(404, response.status_code)

        self.compare_values(u'Neighbor 1000 do not exist.',
                            response.data['detail'])
Ejemplo n.º 26
0
Archivo: tests.py Proyecto: sheimi/oedu
class shareCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_share_detail(self):
        put = { 'comment'   :   "test",
                'url'       :   "/status/crud/1",
                'type'      :   "status"
               }

        response = self.client.put("/share/crud/", json.dumps(put), "text")
        share = Share.objects.filter(comment="test")[0]
        self.assertEqual(share.url, "/status/crud/1")
        
        post = {'comment' : "test2"}
        response = self.client.post("/share/crud/%d" % share.pk, json.dumps(post), "text")
        share = Share.objects.filter(url="/status/crud/1")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(share.comment, "test2")    
        
        response = self.client.get("/share/crud/%d" % share.pk)
        s = json.loads(response.content)[0]
        self.assertEqual("test2", s["fields"]["comment"])
        
        response = self.client.delete("/share/crud/%d" % share.pk)
        share = Share.objects.filter(comment="test2")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(share))
        
Ejemplo n.º 27
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)
Ejemplo n.º 28
0
Archivo: tests.py Proyecto: sheimi/oedu
class rentCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_rent_detail(self):
        put = { 'title'     :   "test",
                'content'   :   "test",
                'to_teacher':   1,
               }
 
        response = self.client.put("/rent/crud/", json.dumps(put), "text")
        rent = Application.objects.filter(title="test")[0]
        self.assertEqual(rent.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/rent/crud/%d" % rent.pk, json.dumps(post), "text")
        rent = Application.objects.filter(title="test")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(rent.content, "test2")
        
        
        response = self.client.get("/rent/crud/%d" % rent.pk)
        a = json.loads(response.content)[0]
        self.assertEqual("test", a["fields"]["title"])
        
        response = self.client.delete("/rent/crud/%d" % rent.pk)
        rents = Application.objects.filter(title="test")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(rents))
Ejemplo n.º 29
0
class RelationsT(T):
    def setUp(self):
        self.client = Client()
        self.client.login(username='******', password='******')

    def test_has_many_fields_are_added_to_json_outputs(self):
        user = User.objects.get(pk=1)
        uri = reverse('apis:user', kwargs={'pk': user.pk})
        res = self.client.get(uri)
        self.assertEqual(res.status_code, 200)
        data = json.loads(res.content)
        user_data = data['user']
        self.assertEqual(user_data['id'], user.pk)

        user = User.objects.get(pk=2)
        uri = reverse('apis:user', kwargs={'pk': user.pk})
        res = self.client.get(uri)
        self.assertEqual(res.status_code, 200)
        data = json.loads(res.content)
        user_data = data['user']
        self.assertEqual(user_data['id'], user.pk)

    def test_dependant_records_are_deleted_on_delete(self):
        user = User.objects.get(pk=1)
        uri = reverse('apis:user', kwargs={'pk': user.pk})
        res = self.client.delete(uri)
        self.assertEqual(res.status_code, 200)

        # assert no post exists
        self.assertEqual(Post.objects.all().count(), 1)
        # assert non dependencies are not affected
        self.assertEqual(Tag.objects.all().count(), 2)
        self.assertEqual(Comment.objects.all().count(), 2)
Ejemplo n.º 30
0
Archivo: tests.py Proyecto: sheimi/oedu
class QuestionCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_index(self):
        pass
        
    def test_question_detail(self):
        put = { 'title'     :   "test",
                'content'   :   "test",
                'receiver'     :  1,
               }
        
        response = self.client.put("/qa/crud/", json.dumps(put), "text")
        question = Question.objects.filter(title="test")[0]
        self.assertEqual(question.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/qa/crud/%d" % question.pk, json.dumps(post), "text")
        question = Question.objects.filter(title="test")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(question.content, "test2")
        
        response = self.client.get("/qa/crud/%d" % question.pk)
        f = json.loads(response.content)[0]
        self.assertEqual("test", f["fields"]["title"])
        
        response = self.client.delete("/qa/crud/%d" % question.pk)
        questions = Question.objects.filter(title="test")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(questions))
Ejemplo n.º 31
0
    def test_error_handling(self):
        c = Client()

        label = 'ATestLabel'

        post_data = {
            'label': label,
            }
        r = c.post(
            '/api/simple-resource',
            data=simplejson.dumps(post_data),
            content_type='application/json')
        data = obj_data = simplejson.loads(r.content)
        self.assertEquals(200, r.status_code)

        r = c.put(
            '/api/simple-resource/%s' % data['pk'],
            data=simplejson.dumps({'nicknames': ['a', 'b', 'c', 'd', 'e', 'f']}),
            content_type='application/json')
        data = simplejson.loads(r.content)
        self.assertEquals(400, r.status_code)

        # Illegal method
        r = c.delete(
            '/api/simple-resource',
            content_type='application/json')
        self.assertEquals(405, r.status_code)

        r = c.get('/api/simple-resource/%s?denyMe=true' % obj_data['pk'])
        self.assertEquals(403, r.status_code)
Ejemplo n.º 32
0
class ApiClient(object):
    def __init__(self, api_key, api_secret, auth_key=None):
        self.api_key = api_key
        self.api_secret = api_secret
        self.auth_key = auth_key
        self.client = Client()

    def _update_params(self, url_path, params, data):
        params.update({"api_key": self.api_key})
        if self.auth_key:
            params.update({"auth_key": self.auth_key})

        # get data from request
        data = {k: v for k, v in data.items()}
        data.update({k: v for k, v in params.items()})

        # generate signature
        sorted_keys = sorted(data.keys())
        message = "%s%s%s" % (url_path,
                "".join("%s=%s" % (k, data[k]) for k in sorted_keys),
                self.api_secret)
        sha = hashlib.sha1()
        sha.update(message)
        api_sig = sha.hexdigest()
        params.update({"api_sig": api_sig})

    def get(self, url_path, params=None, **kwargs):
        if not params:
            params = {}
        self._update_params(url_path, params, {})
        return self.client.get(url_path, params, **kwargs)

    def post(self, url_path, params=None, data=None, **kwargs):
        if not params:
            params = {}
        if not data:
            data = {}
        self._update_params(url_path, params, data)
        url = "%s?%s" % (url_path, "&".join("%s=%s" % (k, v) for k, v in params.items()))
        body = "&".join("%s=%s" % (k, v) for k, v in data.items())
        return self.client.post(url, data=body, content_type=CONTENT_TYPE, **kwargs)

    def put(self, url_path, params=None, data=None, **kwargs):
        if not params:
            params = {}
        if not data:
            data = {}
        self._update_params(url_path, params, data)
        url = "%s?%s" % (url_path, "&".join("%s=%s" % (k, v) for k, v in params.items()))

        body = "&".join("%s=%s" % (k, v) for k, v in data.items())
        return self.client.put(
            url, data=body, content_type=CONTENT_TYPE, **kwargs)

    def delete(self, url_path, params=None, **kwargs):
        if not params:
            params = {}
        self._update_params(url_path, params, {})
        url = "%s?%s" % (url_path, "&".join("%s=%s" % (k, v) for k, v in params.items()))
        return self.client.delete(url, **kwargs)
Ejemplo n.º 33
0
Archivo: tests.py Proyecto: sheimi/oedu
class MailCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        a = self.client.login(username="******", password="******")
        
    def test_get_mail_list(self):
        pass
        
    def test_mail_detail(self):
        put = { 'title'     :   "testt",
                'message'   :   "test",
                'to_user'  :   1,
               }
        
        response = self.client.put("/mail/crud/", json.dumps(put), "text")
        mail = Mail.objects.filter(title="testt")[0]
        self.assertEqual(mail.message, "test")
        
        post = {'message' : "test2"}
        response = self.client.post("/mail/crud/%d" % mail.pk, json.dumps(post), "text")
        mail = Mail.objects.filter(title="testt")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(mail.message, "test2")
        
        
        response = self.client.get("/mail/crud/%d" % mail.pk)
        f = json.loads(response.content)[0]
        self.assertEqual("testt", f["fields"]["title"])
        
        response = self.client.delete("/mail/crud/%d" % mail.pk)
        mail = Mail.objects.filter(title="testt")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(mail))
Ejemplo n.º 34
0
Archivo: tests.py Proyecto: sheimi/oedu
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))
        
Ejemplo n.º 35
0
Archivo: tests.py Proyecto: sheimi/oedu
class AnswerCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_answer_detail(self):
        put = { 'content'       :   "test",
                'question_id'  :   1,
               }
        
        response = self.client.put("/qa/answer/crud/", json.dumps(put), "text")
        answer = Answer.objects.filter(content="test")
        self.assertEqual(1, len(answer))
   
        post = {'content' : "test2"}
        response = self.client.post("/qa/answer/crud/%d" % answer[0].pk, json.dumps(post), "text")
        answer = Answer.objects.filter(content="test2")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(answer[0].content, "test2")
       
        response = self.client.get("/qa/answer/crud/%d" % answer[0].pk)
        a = json.loads(response.content)[0]
        self.assertEqual("test2", a["fields"]["content"])
     
        response = self.client.delete("/qa/answer/crud/%d" % answer[0].pk)
        questions = Answer.objects.filter(content="test2")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(questions))   
Ejemplo n.º 36
0
 def test_if_playlist_found(self):
     # Profile setup
     profile = Profile.objects.create()
     for _ in xrange(2):
         profile.create_playlist()
     # Client setup
     client = Client()
     # Session setup
     from django.conf import settings
     from django.utils.importlib import import_module
     engine = import_module(settings.SESSION_ENGINE)
     store = engine.SessionStore()
     store.save()
     client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
     # Session
     session = client.session
     session['profile_id'] = profile.id
     session.save()
     # Response
     response = client.delete('/playlists/2/delete/',
                              HTTP_X_REQUESTED_WITH='XMLHttpRequest')
     content = json.loads(response.content)
     expected_content = {'success': True}
     self.assertEqual(content, expected_content)
     self.assertEqual(profile.playlists.count(), 1)
Ejemplo n.º 37
0
Archivo: tests.py Proyecto: sheimi/oedu
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))
Ejemplo n.º 38
0
Archivo: tests.py Proyecto: sheimi/oedu
class FeedbackCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        a = self.client.login(username="******", password="******")
        
    def test_get_feedback_list(self):
        pass
        
    def test_feedback_detail(self):
        put = { 'title'     :   "test",
                'content'   :   "test",
                'receiver'  :   1,
               }
        
        response = self.client.put("/feedback/crud/", json.dumps(put), "text")
        feedback = Feedback.objects.filter(title="test")[0]
        self.assertEqual(feedback.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/feedback/crud/%d" % feedback.pk, json.dumps(post), "text")
        feedback = Feedback.objects.filter(title="test")[0]
        self.assertEqual(response.content, '"success"')
        self.assertEqual(feedback.content, "test2")
        
        
        response = self.client.get("/feedback/crud/%d" % feedback.pk)
        f = json.loads(response.content)[0]
        self.assertEqual("test", f["fields"]["title"])
        
        response = self.client.delete("/feedback/crud/%d" % feedback.pk)
        feedback = Feedback.objects.filter(title="test")
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(feedback))
Ejemplo n.º 39
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")
Ejemplo n.º 40
0
    def _delete(self,
                view_name,
                client=None,
                params=None,
                get_params=None,
                follow=False,
                view_args=None,
                view_kwargs=None,
                secure=False,
                **extra):
        """Wrapper for performing an HTTP DELETE request
        """
        params = {} if params is None else params
        get_params = {} if get_params is None else get_params
        view_args = [] if view_args is None else view_args
        view_kwargs = {} if view_kwargs is None else view_kwargs
        path = reverse(view_name, args=view_args, kwargs=view_kwargs)
        if get_params:
            query_string = urlencode(get_params)
            path = '%s?%s' % (
                path,
                query_string,
            )

        if type(client) != Client:
            client = Client()
        response = client.delete(path,
                                 data=params,
                                 follow=follow,
                                 secure=secure,
                                 **extra)
        return response
Ejemplo n.º 41
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)
Ejemplo n.º 42
0
class SimpleTest(TestCase):

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

    def canPostAndRetrieveMessage(self):
        textToPost = 'a fun text message to Gleet!'

        response = self.client.post("/messages", {'message' : textToPost})
        self.assertEqual(200, response.status_code)
        message = list(serializers.deserialize("json", response.content))[0]
        self.assertEqual(textToPost, message.object.message)

        response = self.client.get("/messages")
        deserializedMessage = None
        messages = serializers.deserialize("json", response.content)
        for message in messages:
            deserializedMessage = message.object
            self.assertEqual(textToPost, deserializedMessage.message)
            self.assertNotEqual(None, deserializedMessage.timestamp)

        response = self.client.delete("/messages/" + str(deserializedMessage.id))
        self.assertEqual(200, response.status_code)

        messages = serializers.deserialize("json", self.client.get("/messages").content)
        self.assertEqual(0, len(list(messages)))

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

        self.assertEqual(200, response.status_code)
Ejemplo n.º 43
0
class EquipmentDeleteErrorTestCase(NetworkApiTestCase):

    fixtures = [
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/api_equipment/fixtures/initial_pre_equipment.json',
        'networkapi/api_equipment/fixtures/initial_base.json',
    ]

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

    def tearDown(self):
        pass

    def test_delete_one_inexistent_equipment(self):
        """Test of error to delete of one inexistent equipment."""

        response = self.client.delete(
            '/api/v3/equipment/10/',
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(404, response.status_code)

        self.compare_values(
            'Dont there is a equipament by pk = 10.',
            response.data['detail'])
Ejemplo n.º 44
0
Archivo: tests.py Proyecto: sheimi/oedu
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))
Ejemplo n.º 45
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), '')
Ejemplo n.º 46
0
Archivo: tests.py Proyecto: sheimi/oedu
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))
Ejemplo n.º 47
0
    def test_deleting_a_capability(self):
        """
        Tests deleting 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': '******'})

        response = c.delete(url)
        self.assertEqual(response.status_code, 204)

        # make sure it actually deleted the object.
        with self.assertRaises(Staffing.DoesNotExist):
            Staffing.objects.get(id=capability.id)
Ejemplo n.º 48
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
Ejemplo n.º 49
0
class ProjectTest(FixtureTestCase):
    """Test Project() API"""
    def setUp(self):
        self.project_data = dict(
            name="PyPy",
            repo_type="M",
            repo_path="ssh://[email protected]/pypy/pypy",
            repo_user="******",
            repo_pass="******",
        )
        self.project_data2 = dict(
            name="project alpha",
            repo_type="M",
            repo_path="ssh://[email protected]/pypy/pypy",
            repo_user="******",
            repo_pass="******",
        )
        self.project = Project(**self.project_data)
        self.project.save()
        self.client = Client()
        super(ProjectTest, self).setUp()

    def test_get_project(self):
        """Should get an existing project"""
        response = self.client.get('/api/v1/project/{0}/'.format(
            self.project.id, ))
        self.assertEquals(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content)['name'],
            "{0}".format(self.project_data['name']))

    def test_get_project_all_fields(self):
        """Should get all fields for a project"""
        response = self.client.get('/api/v1/project/%s/' % (self.project.id, ))
        self.assertEquals(response.status_code, 200)
        for k in self.project_data.keys():
            self.assertEqual(
                json.loads(response.content)[k], getattr(self.project, k))

    def test_post(self):
        """Should save a new project"""
        response = self.client.post('/api/v1/project/',
                                    data=json.dumps(self.project_data2),
                                    content_type='application/json')
        self.assertEquals(response.status_code, 201)
        response = self.client.get('/api/v1/project/{0}/'.format(
            self.project.id))
        for k, v in self.project_data.items():
            self.assertEqual(json.loads(response.content)[k], v)

    def test_delete(self):
        """Should delete an project"""
        response = self.client.delete('/api/v1/project/{0}/'.format(
            self.project.id, ),
                                      content_type='application/json')
        self.assertEquals(response.status_code, 204)

        response = self.client.get('/api/v1/project/{0}/'.format(
            self.project.id, ))
        self.assertEquals(response.status_code, 404)
Ejemplo n.º 50
0
 def test_permission_allowed(self):
     c = Client()
     c.login(username='******', password='******')
     response = c.delete('/rest/security_test/1')
     self.assertEquals(response.status_code, 204)
     st = SecurityTest.objects.filter(pk=1)
     self.assertEquals(len(st), 0)
Ejemplo n.º 51
0
    def test_actual_delete_no_etag(self):
        c = Client()

        response = c.delete(self.url)
        self.assertEqual(response.status_code, 400)

        response = c.get(self.url)
        self.assertEqual(response.status_code, 200)
Ejemplo n.º 52
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()
         response = c.delete("/api/v1/spot/aa")
         self.assertEquals(response.status_code, 404,
                           "Rejects an invalid url")
Ejemplo n.º 53
0
 def test_invalid_id_too_high(self):
     dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')
     with patch.object(models, 'cache', dummy_cache):
         c = Client()
         test_id = self.spot.pk + 10000
         test_url = '/api/v1/spot/{0}'.format(test_id)
         response = c.delete(test_url)
         self.assertEquals(response.status_code, 404, "Rejects a not-yet existant url")
Ejemplo n.º 54
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)
Ejemplo n.º 55
0
    def test_invalid_id_too_high(self):
        c = Client()

        # GIF
        test_gif_id = self.gif.pk + 10000
        test_url = "/api/v1/spot/%s/image/%s" % (self.url, test_gif_id)
        response = c.delete(test_url)
        self.assertEquals(response.status_code, 404)
Ejemplo n.º 56
0
    def test_user_login_invalid(self, mock_check_database_status,
                                mock_acl_from_hell):
        """It tests user is not authenticated."""
        client = Client()
        url = reverse('tsuru:service-app-bind', args=('dev', 'test_database'))
        response = client.delete(url, {'app-name': 'test-app'})

        self.assertEquals(response.status_code, 401)
Ejemplo n.º 57
0
    def test_actual_delete_no_etag(self):
        c = Client()

        response = c.delete(self.url)
        self.assertEqual(response.status_code, 400)

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