Example #1
0
class TestService(TestCase):

    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_404(self):
        # a get on a resource that explicitely return a 404 should return
        # 404
        self.app.get("/service", status=404)

    def test_405(self):
        # calling a unknown verb on an existing resource should return a 405
        self.app.post("/service", status=405)

    def test_acl_support(self):
        self.app.delete('/service')

    def test_class_support(self):
        self.app.get('/fresh-air', status=400)
        resp = self.app.get('/fresh-air', headers={'X-Temperature': '50'})
        self.assertEquals(resp.body, 'fresh air')
Example #2
0
def test_delete_pages(town_app):
    client = Client(town_app)

    root_url = client.get('/').pyquery('.top-bar-section a').attr('href')

    login_page = client.get('/login?to={}'.format(root_url))
    login_page.form['email'] = '*****@*****.**'
    login_page.form['password'] = '******'

    root_page = login_page.form.submit().follow()
    new_page = root_page.click('Thema')

    new_page.form['title'] = "Living in Govikon is Swell"
    new_page.form['text'] = (
        "## Living in Govikon is Really Great\n"
        "*Experts say it's the fact that Govikon does not really exist.*"
    )
    page = new_page.form.submit().follow()
    delete_link = page.pyquery('a[ic-delete-from]')[0].attrib['ic-delete-from']

    result = client.delete(delete_link.split('?')[0], expect_errors=True)
    assert result.status_code == 403

    assert client.delete(delete_link).status_code == 200
    assert client.delete(delete_link, expect_errors=True).status_code == 404
Example #3
0
class Detalle(TestCase):
    """
    NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase 
    """

    @classmethod
    def setUpClass(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[1]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)

        res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)

    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)

    def test_detalle_usuario(self):
        res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token) 
        respuesta = res.json_body['mensaje'][0]['givenName']
        datos = self.datos['corpus']['givenName']
        
        self.assertEqual(respuesta, datos)

    def test_detalle_claves(self):
        claves = ['dn', 'givenName', 'cn']

        res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token)
        respuesta = res.json_body['mensaje'][0].keys()
        self.assertListEqual(respuesta, claves)

    def test_detalle_claves_noexistentes(self):
        claves = ['dn', 'givenName', 'cn', 'noexistente']

        res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token)
        respuesta = res.json_body['mensaje'][0].keys()
        del claves[claves.index('noexistente')]
        
        self.assertListEqual(respuesta, claves)
    
    def test_detalle_noexistente(self):
        uid = 'fitzcarraldo'
        self.testapp.get('/usuarios/' + uid, status=404, headers=self.token)
        
    def test_detalle_unauth(self):
        self.testapp.post_json('/usuarios' + self.uid, status=404)
Example #4
0
def test_people_view(town_app):
    client = Client(town_app)

    login_page = client.get('/login')
    login_page.form.set('email', '*****@*****.**')
    login_page.form.set('password', 'hunter2')
    login_page.form.submit()

    people = client.get('/personen')
    assert 'noch keine Personen' in people

    new_person = people.click('Person')
    new_person.form['first_name'] = 'Flash'
    new_person.form['last_name'] = 'Gordon'
    person = new_person.form.submit().follow()

    assert 'Flash Gordon' in person

    people = client.get('/personen')

    assert 'Flash Gordon' in people

    edit_person = person.click('Bearbeiten')
    edit_person.form['first_name'] = 'Merciless'
    edit_person.form['last_name'] = 'Ming'
    person = edit_person.form.submit().follow()

    assert 'Merciless Ming' in person

    client.delete(person.request.url)

    people = client.get('/personen')
    assert 'noch keine Personen' in people
Example #5
0
    def test_custom_with_trailing_slash(self):

        class CustomController(RestController):

            _custom_actions = {
                'detail': ['GET'],
                'create': ['POST'],
                'update': ['PUT'],
                'remove': ['DELETE'],
            }

            @expose()
            def detail(self):
                return 'DETAIL'

            @expose()
            def create(self):
                return 'CREATE'

            @expose()
            def update(self, id):
                return id

            @expose()
            def remove(self, id):
                return id

        app = TestApp(make_app(CustomController()))

        r = app.get('/detail')
        assert r.status_int == 200
        assert r.body == b_('DETAIL')

        r = app.get('/detail/')
        assert r.status_int == 200
        assert r.body == b_('DETAIL')

        r = app.post('/create')
        assert r.status_int == 200
        assert r.body == b_('CREATE')

        r = app.post('/create/')
        assert r.status_int == 200
        assert r.body == b_('CREATE')

        r = app.put('/update/123')
        assert r.status_int == 200
        assert r.body == b_('123')

        r = app.put('/update/123/')
        assert r.status_int == 200
        assert r.body == b_('123')

        r = app.delete('/remove/456')
        assert r.status_int == 200
        assert r.body == b_('456')

        r = app.delete('/remove/456/')
        assert r.status_int == 200
        assert r.body == b_('456')
Example #6
0
    def test_custom_with_trailing_slash(self):

        class CustomController(RestController):

            _custom_actions = {
                'detail': ['GET'],
                'create': ['POST'],
                'update': ['PUT'],
                'remove': ['DELETE'],
            }

            @expose()
            def detail(self):
                return 'DETAIL'

            @expose()
            def create(self):
                return 'CREATE'

            @expose()
            def update(self, id):
                return id

            @expose()
            def remove(self, id):
                return id

        app = TestApp(make_app(CustomController()))

        r = app.get('/detail')
        assert r.status_int == 200
        assert r.body == b_('DETAIL')

        r = app.get('/detail/')
        assert r.status_int == 200
        assert r.body == b_('DETAIL')

        r = app.post('/create')
        assert r.status_int == 200
        assert r.body == b_('CREATE')

        r = app.post('/create/')
        assert r.status_int == 200
        assert r.body == b_('CREATE')

        r = app.put('/update/123')
        assert r.status_int == 200
        assert r.body == b_('123')

        r = app.put('/update/123/')
        assert r.status_int == 200
        assert r.body == b_('123')

        r = app.delete('/remove/456')
        assert r.status_int == 200
        assert r.body == b_('456')

        r = app.delete('/remove/456/')
        assert r.status_int == 200
        assert r.body == b_('456')
 def test_delete_404(self):
     wsgiapp = self.config.make_wsgi_app()
     app = TestApp(wsgiapp)
     request = testing.DummyRequest()
     apply_request_extensions(request)
     self._fixture(request)
     app.delete('/api/1/walls/2/collections/404', status=404)
Example #8
0
class TestService(TestCase):
    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_404(self):
        # a get on a resource that explicitely return a 404 should return
        # 404
        self.app.get("/service", status=404)

    def test_405(self):
        # calling a unknown verb on an existing resource should return a 405
        self.app.post("/service", status=405)

    def test_acl_support(self):
        self.app.delete('/service')

    def test_class_support(self):
        self.app.get('/fresh-air', status=400)
        resp = self.app.get('/fresh-air', headers={'X-Temperature': '50'})
        self.assertEqual(resp.body, b'fresh air with context!')
Example #9
0
class FunctionalTest(unittest.TestCase):
    def setUp(self):
        self.app = TestApp(application) 

    def test_index_returns_200(self):  
        response = self.app.get('/', expect_errors=True)        
        self.assertEquals("200 OK", response.status)
            
    def test_index_return_correct_mime_type(self):
        response = self.app.get('/', expect_errors=True)
        self.assertEquals(response.content_type, "text/html")
        
    def test_multiple_args_in_url(self):
        response = self.app.get('/foo/1/2', expect_errors=True)        
        response.mustcontain("Hello World of 1 and 2")

    def test_put(self):
        response = self.app.put('/', expect_errors=True)        
        self.assertEquals("200 OK", response.status)
        response.mustcontain("Hello World of Put")
        
    def test_404_handler(self):  
        response = self.app.get('/does-not-exist', expect_errors=True)        
        self.assertEquals("404 Not Found", response.status)

    def test_404_handler(self):  
        response = self.app.get('/does-not-exist', expect_errors=True)        
        self.assertEquals("404 Not Found", response.status)

    def test_HTTPResponseRedirect_handler(self):
        response = self.app.get('/bar', expect_errors=True)        
        self.assertEquals("/", response.headers['Location'])
        self.assertEquals("301 Moved Permanently", response.status)

    def test_temporaty_HTTPResponseRedirect_handler(self):
        response = self.app.delete('/bar', expect_errors=True)        
        self.assertEquals("/", response.headers['Location'])
        self.assertEquals("302 Found", response.status)

    def test_unregistered_post_request(self):
        response = self.app.post('/', expect_errors=True)        
        self.assertEquals("405 Method Not Allowed", response.status)

    def test_unregistered_delete_request(self):
        response = self.app.delete('/', expect_errors=True)        
        self.assertEquals("405 Method Not Allowed", response.status)

    def test_unregistered_put_request(self):
        response = self.app.put('/bar', expect_errors=True)        
        self.assertEquals("405 Method Not Allowed", response.status)

    def test_query_string(self):  
        response = self.app.get('/?test=test', expect_errors=True)        
        self.assertEqual("test", response.request.GET['test'])
        self.assertEquals("200 OK", response.status)

    def test_addition_of_method_to_request(self):  
        response = self.app.get('/', expect_errors=True)        
        self.assertEqual("GET", response.request.method)
Example #10
0
class DwarfTestCase(utils.TestCase):

    def setUp(self):
        super(DwarfTestCase, self).setUp()
        self.app = TestApp(ApiServer().app)

    # Commented out to silence pylint
    # def tearDown(self):
    #     super(DwarfTestCase, self).tearDown()

    def test_list_flavors(self):
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor1, flavor2, flavor3],
                                           details=False))

    def test_list_flavors_detail(self):
        resp = self.app.get('/compute/v2.0/flavors/detail', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor1, flavor2, flavor3],
                                           details=True))

    def test_show_flavor(self):
        resp = self.app.get('/compute/v2.0/flavors/%s' % flavor1['id'],
                            status=200)
        self.assertEqual(json.loads(resp.body), show_flavor_resp(flavor1))

    def test_delete_flavor(self):
        # Delete flavor[0]
        resp = self.app.delete('/compute/v2.0/flavors/%s' % flavor1['id'],
                               status=200)
        self.assertEqual(resp.body, '')

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor2, flavor3], details=False))

    def test_create_flavor(self):
        # Delete flavor[0]
        self.app.delete('/compute/v2.0/flavors/%s' % flavor1['id'], status=200)

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor2, flavor3], details=False))

        # (Re-)create flavor[0]
        resp = self.app.post('/compute/v2.0/flavors',
                             params=json.dumps(create_flavor_req(flavor1)),
                             status=200)
        self.assertEqual(json.loads(resp.body), create_flavor_resp(flavor1))

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor2, flavor3, flavor1],
                                           details=False))
Example #11
0
class DwarfTestCase(utils.TestCase):
    def setUp(self):
        super(DwarfTestCase, self).setUp()
        self.app = TestApp(ApiServer().app)

    # Commented out to silence pylint
    # def tearDown(self):
    #     super(DwarfTestCase, self).tearDown()

    def test_list_flavors(self):
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(
            json.loads(resp.body),
            list_flavors_resp([flavor1, flavor2, flavor3], details=False))

    def test_list_flavors_detail(self):
        resp = self.app.get('/compute/v2.0/flavors/detail', status=200)
        self.assertEqual(
            json.loads(resp.body),
            list_flavors_resp([flavor1, flavor2, flavor3], details=True))

    def test_show_flavor(self):
        resp = self.app.get('/compute/v2.0/flavors/%s' % flavor1['id'],
                            status=200)
        self.assertEqual(json.loads(resp.body), show_flavor_resp(flavor1))

    def test_delete_flavor(self):
        # Delete flavor[0]
        resp = self.app.delete('/compute/v2.0/flavors/%s' % flavor1['id'],
                               status=200)
        self.assertEqual(resp.body, '')

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor2, flavor3], details=False))

    def test_create_flavor(self):
        # Delete flavor[0]
        self.app.delete('/compute/v2.0/flavors/%s' % flavor1['id'], status=200)

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_flavors_resp([flavor2, flavor3], details=False))

        # (Re-)create flavor[0]
        resp = self.app.post('/compute/v2.0/flavors',
                             params=json.dumps(create_flavor_req(flavor1)),
                             status=200)
        self.assertEqual(json.loads(resp.body), create_flavor_resp(flavor1))

        # Check the resulting list of flavors
        resp = self.app.get('/compute/v2.0/flavors', status=200)
        self.assertEqual(
            json.loads(resp.body),
            list_flavors_resp([flavor2, flavor3, flavor1], details=False))
Example #12
0
def test_feed_delete():
    app = Application(application)
    with test_database(temp_db, (Feed, Item)):
        app.post('/api/feeds',
                 json.dumps(feed_data),
                 content_type='application/json')
        feed = list(Feed.select())[0]
        app.delete('/api/feeds?id={}'.format(feed.id))
        all_feeds = list(Feed.select())
        assert len(all_feeds) == 0
Example #13
0
def test_DELETE_url(testapp: TestApp, db: Session, democontent: None) -> None:
    """Test DELETE /api/urls/{slug}."""
    assert Url.by_slug("foo", db=db) is not None
    testapp.delete(
        "/api/urls/foo",
        headers={"Authorization": f"Token {USER_ONE_JWT}"},
        status=200,
    )

    assert Url.by_slug("foo", db=db) is None
Example #14
0
class Creacion(TestCase):
    """
    NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase 
    """

    @classmethod
    def setUp(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[0]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)

    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)

    def test_creacion(self):
        res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)
        respuesta = res.location
        self.assertEqual(respuesta, 'http://localhost/usuarios/%s' % self.uid)

    def test_creacion_no_json(self):
        datos = "Mínimo esfuerzo para máximo daño"
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_creacion_corpus_faltante(self):
        datos = {'cuerpo': self.datos['corpus'].copy()}
        
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_creacion_usuario_existente(self):
        self.testapp.post_json('/usuarios', status=409, params=self.datos, headers=self.token)
   
    def test_creacion_usuario_datos_inconsistente(self):
        datos = self.datos.copy()
        datos['corpus']['grupo'] = "0"
        datos['corpus']['uid'] = "nuevoUsuario"
        
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_usuarios_creacion_unauth(self):
        self.testapp.post_json('/usuarios', status=403, params=self.datos)
Example #15
0
    def test_clienttester(self):

        app = TestApp(ClientTesterMiddleware(SomeApp()))

        # that calls the app
        app.get('/bleh', status=200)

        # let's ask for a 503 and then a 400
        app.post('/__testing__', params=_d({'status': 503}))
        app.post('/__testing__', params=_d({'status': 400}))

        app.get('/buh', status=503)
        app.get('/buh', status=400)

        # back to normal
        app.get('/buh', status=200)

        # let's ask for two 503s
        app.post('/__testing__',
                 params=_d({'status': 503, 'repeat': 2}))

        app.get('/buh', status=503)
        app.get('/buh', status=503)
        app.get('/buh', status=200)

        # some headers and body now
        app.post('/__testing__',
                params=_d({'status': 503, 'body': 'oy',
                           'headers': {'foo': '1'}}))

        res = app.get('/buh', status=503)
        self.assertEqual(res.body, 'oy')
        self.assertEqual(res.headers['foo'], '1')

        # repeat stuff indefinitely
        app.post('/__testing__',
                params=_d({'status': 503, 'body': 'oy',
                           'headers': {'foo': '1'},
                           'repeat': -1}))

        for i in range(20):
            app.get('/buh', status=503)

        # let's wipe out the pile
        app.delete('/__testing__')
        app.get('/buh', status=200)

        # a bit of timing now
        app.post('/__testing__',
                params=_d({'status': 503, 'delay': .5}))
        now = time.time()
        app.get('/buh', status=503)
        then = time.time()
        self.assertTrue(then - now >= .5)
Example #16
0
    def test_simple_nested_rest(self):

        class BarController(RestController):

            @expose()
            def post(self):
                return "BAR-POST"

            @expose()
            def delete(self, id_):
                return "BAR-%s" % id_

            @expose()
            def post(self):
                return "BAR-POST"

            @expose()
            def delete(self, id_):
                return "BAR-%s" % id_

        class FooController(RestController):

            bar = BarController()

            @expose()
            def post(self):
                return "FOO-POST"

            @expose()
            def delete(self, id_):
                return "FOO-%s" % id_

        class RootController(object):
            foo = FooController()

        # create the app
        app = TestApp(make_app(RootController()))

        r = app.post('/foo')
        assert r.status_int == 200
        assert r.body == "FOO-POST"

        r = app.delete('/foo/1')
        assert r.status_int == 200
        assert r.body == "FOO-1"

        r = app.post('/foo/bar')
        assert r.status_int == 200
        assert r.body == "BAR-POST"

        r = app.delete('/foo/bar/2')
        assert r.status_int == 200
        assert r.body == "BAR-2"
Example #17
0
    def test_singular_resource(self, *a):
        View = get_test_view_class()
        config = _create_config()
        root = config.get_root_resource()
        root.add('thing', view=View)
        grandpa = root.add('grandpa', 'grandpas', view=View)
        wife = grandpa.add('wife', view=View, renderer='string')
        wife.add('child', 'children', view=View)

        config.begin()
        app = TestApp(config.make_wsgi_app())

        self.assertEqual(
            '/grandpas/1/wife',
            route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1)
        )

        self.assertEqual(
            '/grandpas/1',
            route_path('grandpa', testing.DummyRequest(), id=1)
        )

        self.assertEqual(
            '/grandpas/1/wife/children/2',
            route_path('grandpa_wife:child', testing.DummyRequest(),
                       grandpa_id=1, id=2)
        )

        self.assertEqual(app.put('/grandpas').body, six.b('update_many'))
        self.assertEqual(app.head('/grandpas').body, six.b(''))
        self.assertEqual(app.options('/grandpas').body, six.b(''))

        self.assertEqual(app.delete('/grandpas/1').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1').body, six.b(''))

        self.assertEqual(app.put('/thing').body, six.b('replace'))
        self.assertEqual(app.patch('/thing').body, six.b('update'))
        self.assertEqual(app.delete('/thing').body, six.b('delete'))
        self.assertEqual(app.head('/thing').body, six.b(''))
        self.assertEqual(app.options('/thing').body, six.b(''))

        self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace'))
        self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update'))
        self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1/wife').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1/wife').body, six.b(''))

        self.assertEqual(six.b('show'), app.get('/grandpas/1').body)
        self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body)
        self.assertEqual(
            six.b('show'), app.get('/grandpas/1/wife/children/1').body)
Example #18
0
    def test_singular_resource(self, *a):
        View = get_test_view_class()
        config = _create_config()
        root = config.get_root_resource()
        root.add('thing', view=View)
        grandpa = root.add('grandpa', 'grandpas', view=View)
        wife = grandpa.add('wife', view=View, renderer='string')
        wife.add('child', 'children', view=View)

        config.begin()
        app = TestApp(config.make_wsgi_app())

        self.assertEqual(
            '/grandpas/1/wife',
            route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1)
        )

        self.assertEqual(
            '/grandpas/1',
            route_path('grandpa', testing.DummyRequest(), id=1)
        )

        self.assertEqual(
            '/grandpas/1/wife/children/2',
            route_path('grandpa_wife:child', testing.DummyRequest(),
                       grandpa_id=1, id=2)
        )

        self.assertEqual(app.put('/grandpas').body, six.b('update_many'))
        self.assertEqual(app.head('/grandpas').body, six.b(''))
        self.assertEqual(app.options('/grandpas').body, six.b(''))

        self.assertEqual(app.delete('/grandpas/1').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1').body, six.b(''))

        self.assertEqual(app.put('/thing').body, six.b('replace'))
        self.assertEqual(app.patch('/thing').body, six.b('update'))
        self.assertEqual(app.delete('/thing').body, six.b('delete'))
        self.assertEqual(app.head('/thing').body, six.b(''))
        self.assertEqual(app.options('/thing').body, six.b(''))

        self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace'))
        self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update'))
        self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1/wife').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1/wife').body, six.b(''))

        self.assertEqual(six.b('show'), app.get('/grandpas/1').body)
        self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body)
        self.assertEqual(
            six.b('show'), app.get('/grandpas/1/wife/children/1').body)
Example #19
0
def test_delete_builtin_form(town_app):
    client = Client(town_app)
    builtin_form = '/formular/wohnsitzbestaetigung'

    response = client.delete(builtin_form, expect_errors=True)
    assert response.status_code == 403

    login_page = client.get('/login')
    login_page.form.set('email', '*****@*****.**')
    login_page.form.set('password', 'hunter2')
    login_page.form.submit()

    response = client.delete(builtin_form, expect_errors=True)
    assert response.status_code == 403
Example #20
0
def test_delete_custom_form(town_app):
    client = Client(town_app)

    login_page = client.get('/login')
    login_page.form.set('email', '*****@*****.**')
    login_page.form.set('password', 'hunter2')
    login_page.form.submit()

    form_page = client.get('/formulare/neu')
    form_page.form['title'] = "My Form"
    form_page.form['definition'] = "e-mail * = @@@"
    form_page = form_page.form.submit().follow()

    client.delete(
        form_page.pyquery('a.delete-link')[0].attrib['ic-delete-from'])
Example #21
0
def test_delete_supercar():
    supercars[1] = {'engine': '1'}
    app = TestApp(default_app())

    resp = app.delete('/supercars/1')
    assert_equal(resp.status, '200 OK')
    app.reset()
Example #22
0
class TestShield(unittest.TestCase):

    def setUp(self):
        self.app = TestApp(application)

    def test_shields(self):
        response = self.app.post_json('/api/_login', {"username": "******", "password": '******'})
        self.assertEqual(200, response.status_int)

        response = self.app.get('/api/person/')
        self.assertEqual(200, response.status_int)

        self.app = TestApp(application)
        response = self.app.get('/api/person', expect_errors=True)
        self.assertEquals(401, response.status_int)

        self.app = TestApp(application)
        response = self.app.post('/api/person/', expect_errors=True)
        self.assertIsNot(401, response.status_int)

        self.app = TestApp(application)
        response = self.app.put('/api/person/', expect_errors=True)
        self.assertIsNot(404, response.status_int)

        self.app = TestApp(application)
        response = self.app.delete('/api/person/', expect_errors=True)
        self.assertIsNot(404, response.status_int)
Example #23
0
class ClientTest(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(ClientTest, self).__init__(*args, **kwargs)
        app.debug = True
        self.client = TestApp(app)

    def get(self,
            url,
            params=None,
            headers=None,
            extra_environ=None,
            status=[200, 201, 400, 401, 403, 404],
            expect_errors=False,
            xhr=False):
        self.resp = self.client.get(url, params, headers, extra_environ,
                                    status, expect_errors, xhr)
        return self.resp

    def post(self,
             url,
             params=u'',
             headers=None,
             extra_environ=None,
             status=[200, 201, 400, 401, 403, 404],
             upload_files=None,
             expect_errors=False,
             content_type=None,
             xhr=False):
        self.resp = self.client.post(url, params, headers, extra_environ,
                                     status, upload_files, expect_errors,
                                     content_type, xhr)
        return self.resp

    def put(self,
            url,
            params=u'',
            headers=None,
            extra_environ=None,
            status=[200, 201, 400, 401, 403, 404],
            upload_files=None,
            expect_errors=False,
            content_type=None,
            xhr=False):
        self.resp = self.client.put(url, params, headers, extra_environ,
                                    status, upload_files, expect_errors,
                                    content_type, xhr)
        return self.resp

    def delete(self,
               url,
               params=u'',
               headers=None,
               extra_environ=None,
               status=[200, 201, 400, 401, 403, 404],
               expect_errors=False,
               content_type=None,
               xhr=False):
        self.resp = self.client.delete(url, params, headers, extra_environ,
                                       status, expect_errors, content_type,
                                       xhr)
Example #24
0
def test_delete_user():
    c = Client(App())

    response = c.post(
        "/login", json.dumps({"email": "*****@*****.**", "password": "******"})
    )

    headers = {"Authorization": response.headers["Authorization"]}

    with db_session:
        assert User.exists(nickname="Mary")

    c.delete("/users/2", headers=headers)

    with db_session:
        assert not User.exists(nickname="Mary")
Example #25
0
class DeleteUnidadTrabajo(unittest.TestCase):
    """
    @summary: Testea eliminacion de unidades de trabajo.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = UnidadTrabajoDAO(None)
        nueva_unidad_trabajo = UnidadTrabajo("Prueba", "P", "Prueba", "0")
        dao.crear(nueva_unidad_trabajo)

        unidad = {
            "_nombre": "Prueba 1",
            "id": nueva_unidad_trabajo.id,
            "_etiqueta": "P",
            "_descripcion": "Prueba",
            "_color": "008000"
        }
        direccion = '/unidadtrabajo/' + str(nueva_unidad_trabajo.id)
        res = self.testapp.delete(direccion, params=json.dumps(unidad))
        print "Testeando eliminar recursos"
        self.failUnless('sucess' in res.body)
Example #26
0
    def test_nested_generic(self):

        class SubSubController(object):
            @expose(generic=True)
            def index(self):
                return 'GET'

            @index.when(method='DELETE', template='json')
            def do_delete(self, name, *args):
                return dict(result=name, args=', '.join(args))

        class SubController(object):
            sub = SubSubController()

        class RootController(object):
            sub = SubController()

        app = TestApp(Pecan(RootController()))
        r = app.get('/sub/sub/')
        assert r.status_int == 200
        assert r.body == b_('GET')

        r = app.delete('/sub/sub/joe/is/cool')
        assert r.status_int == 200
        assert r.body == b_(dumps(dict(result='joe', args='is, cool')))
def test_favorite_unfavorite_article(
    testapp: TestApp, db: Session, democontent: None
) -> None:
    """Test POST/DELETE /api/articles/{slug}/favorite."""
    user = User.by_username("one", db=db)
    assert user.favorites == []  # type: ignore

    res = testapp.post_json(
        "/api/articles/foo/favorite",
        headers={"Authorization": f"Token {USER_ONE_JWT}"},
        status=200,
    )
    assert res.json["article"]["favorited"] is True
    assert res.json["article"]["favoritesCount"] == 1
    user = User.by_username("one", db=db)
    assert [article.slug for article in user.favorites] == ["foo"]  # type: ignore

    res = testapp.delete(
        "/api/articles/foo/favorite",
        headers={"Authorization": f"Token {USER_ONE_JWT}"},
        status=200,
    )
    user = User.by_username("one", db=db)
    assert res.json["article"]["favorited"] is False
    assert res.json["article"]["favoritesCount"] == 0
    assert user.favorites == []  # type: ignore
Example #28
0
    def test_nested_generic(self):

        class SubSubController(object):
            @expose(generic=True)
            def index(self):
                return 'GET'

            @index.when(method='DELETE', template='json')
            def do_delete(self, name, *args):
                return dict(result=name, args=', '.join(args))

        class SubController(object):
            sub = SubSubController()

        class RootController(object):
            sub = SubController()

        app = TestApp(Pecan(RootController()))
        r = app.get('/sub/sub/')
        assert r.status_int == 200
        assert r.body == b_('GET')

        r = app.delete('/sub/sub/joe/is/cool')
        assert r.status_int == 200
        assert r.body == b_(dumps(dict(result='joe', args='is, cool')))
Example #29
0
def test_news(town_app):
    client = Client(town_app)

    login_page = client.get('/login')
    login_page.form['email'] = '*****@*****.**'
    login_page.form['password'] = '******'
    page = login_page.form.submit().follow()

    assert len(page.pyquery('.latest-news')) == 0

    page = page.click('Aktuelles', index=1)
    page = page.click('Nachricht')

    page.form['title'] = "We have a new homepage"
    page.form['lead'] = "It is very good"
    page.form['text'] = "It is lots of fun"

    page = page.form.submit().follow()

    assert "We have a new homepage" in page.text
    assert "It is very good" in page.text
    assert "It is lots of fun" in page.text

    page = client.get('/aktuelles')

    assert "We have a new homepage" in page.text
    assert "It is very good" in page.text
    assert "It is lots of fun" not in page.text

    page = client.get('/')

    assert "We have a new homepage" in page.text
    assert "It is very good" in page.text
    assert "It is lots of fun" not in page.text

    page = page.click('weiterlesen...')

    assert "We have a new homepage" in page.text
    assert "It is very good" in page.text
    assert "It is lots of fun" in page.text

    client.delete(page.pyquery('a[ic-delete-from]').attr('ic-delete-from'))
    page = client.get('/aktuelles')

    assert "We have a new homepage" not in page.text
    assert "It is very good" not in page.text
    assert "It is lots of fun" not in page.text
Example #30
0
    def test_bad_rest(self):

        class ThingsController(RestController):
            pass

        class RootController(object):
            things = ThingsController()

        # create the app
        app = TestApp(make_app(RootController()))

        # test get_all
        r = app.get('/things', status=405)
        assert r.status_int == 405

        # test get_one
        r = app.get('/things/1', status=405)
        assert r.status_int == 405

        # test post
        r = app.post('/things', {'value': 'one'}, status=405)
        assert r.status_int == 405

        # test edit
        r = app.get('/things/1/edit', status=405)
        assert r.status_int == 405

        # test put
        r = app.put('/things/1', {'value': 'ONE'}, status=405)

        # test put with _method parameter and GET
        r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405)
        assert r.status_int == 405

        # test put with _method parameter and POST
        r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=405)
        assert r.status_int == 405

        # test get delete
        r = app.get('/things/1/delete', status=405)
        assert r.status_int == 405

        # test delete
        r = app.delete('/things/1', status=405)
        assert r.status_int == 405

        # test delete with _method parameter and GET
        r = app.get('/things/1?_method=DELETE', status=405)
        assert r.status_int == 405

        # test delete with _method parameter and POST
        r = app.post('/things/1?_method=DELETE', status=405)
        assert r.status_int == 405

        # test "RESET" custom action
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.request('/things', method='RESET', status=405)
            assert r.status_int == 405
Example #31
0
    def test_bad_rest(self):

        class ThingsController(RestController):
            pass

        class RootController(object):
            things = ThingsController()

        # create the app
        app = TestApp(make_app(RootController()))

        # test get_all
        r = app.get('/things', status=404)
        assert r.status_int == 404

        # test get_one
        r = app.get('/things/1', status=404)
        assert r.status_int == 404

        # test post
        r = app.post('/things', {'value': 'one'}, status=404)
        assert r.status_int == 404

        # test edit
        r = app.get('/things/1/edit', status=404)
        assert r.status_int == 404

        # test put
        r = app.put('/things/1', {'value': 'ONE'}, status=404)

        # test put with _method parameter and GET
        r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405)
        assert r.status_int == 405

        # test put with _method parameter and POST
        r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=404)
        assert r.status_int == 404

        # test get delete
        r = app.get('/things/1/delete', status=404)
        assert r.status_int == 404

        # test delete
        r = app.delete('/things/1', status=404)
        assert r.status_int == 404

        # test delete with _method parameter and GET
        r = app.get('/things/1?_method=DELETE', status=405)
        assert r.status_int == 405

        # test delete with _method parameter and POST
        r = app.post('/things/1?_method=DELETE', status=404)
        assert r.status_int == 404

        # test "RESET" custom action
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.request('/things', method='RESET', status=404)
            assert r.status_int == 404
Example #32
0
 def test_delete(self):
     wsgiapp = self.config.make_wsgi_app()
     app = TestApp(wsgiapp)
     request = testing.DummyRequest()
     apply_request_extensions(request)
     self._fixture(request)
     response = app.delete('/api/1/walls/2/collections/3', status=200)
     self.assertEqual({"removed": 3}, response.json_body)
    def _test_request(self,
                      swagger_plugin=None,
                      method='GET',
                      url='/thing',
                      route_url=None,
                      request_json=VALID_JSON,
                      response_json=VALID_JSON,
                      headers=None,
                      content_type='application/json',
                      extra_check=lambda *args, **kwargs: True):
        if swagger_plugin is None:
            swagger_plugin = self._make_swagger_plugin()
        if response_json is None:
            response_json = {}
        if route_url is None:
            route_url = url

        bottle_app = Bottle()
        bottle_app.install(swagger_plugin)

        @bottle_app.route(route_url, method)
        def do_thing(*args, **kwargs):
            extra_check(*args, **kwargs)
            return response_json() if hasattr(response_json,
                                              "__call__") else response_json

        test_app = TestApp(bottle_app)
        if method.upper() == 'GET':
            response = test_app.get(url, expect_errors=True, headers=headers)
        elif method.upper() == 'POST':
            if content_type == 'application/json':
                response = test_app.post_json(url,
                                              request_json,
                                              expect_errors=True,
                                              headers=headers)
            else:
                response = test_app.post(url,
                                         request_json,
                                         content_type=content_type,
                                         expect_errors=True,
                                         headers=headers)
        elif method.upper() == 'DELETE':
            if content_type == 'aplication/json':
                response = test_app.delete_json(url,
                                                request_json,
                                                expect_errors=True,
                                                headers=headers)
            else:
                response = test_app.delete(url,
                                           request_json,
                                           content_type=content_type,
                                           expect_errors=True,
                                           headers=headers)
        else:

            raise Exception("Invalid method {}".format(method))

        return response
Example #34
0
    def test_simple_nested_rest(self):

        class BarController(RestController):

            @expose()
            def post(self):
                return "BAR-POST"

            @expose()
            def delete(self, id_):
                return "BAR-%s" % id_

        class FooController(RestController):

            bar = BarController()

            @expose()
            def post(self):
                return "FOO-POST"

            @expose()
            def delete(self, id_):
                return "FOO-%s" % id_

        class RootController(object):
            foo = FooController()

        # create the app
        app = TestApp(make_app(RootController()))

        r = app.post('/foo')
        assert r.status_int == 200
        assert r.body == b_("FOO-POST")

        r = app.delete('/foo/1')
        assert r.status_int == 200
        assert r.body == b_("FOO-1")

        r = app.post('/foo/bar')
        assert r.status_int == 200
        assert r.body == b_("BAR-POST")

        r = app.delete('/foo/bar/2')
        assert r.status_int == 200
        assert r.body == b_("BAR-2")
Example #35
0
 def test_delete(self):
     wsgiapp = self.config.make_wsgi_app()
     app = TestApp(wsgiapp)
     request = testing.DummyRequest()
     apply_request_extensions(request)
     root, cred = self._fixture(request)
     response = app.delete('/api/1/users/10', status=200,
                           headers={'Authorization': cred.header()},)
     self.assertEqual({"removed": 10}, response.json_body)
def test_DELETE_comment(testapp: TestApp, democontent: None) -> None:
    """Test DELETE /api/articles/{slug}/comment/{id}."""
    res = testapp.delete(
        "/api/articles/foo/comments/99",
        headers={"Authorization": f"Token {USER_ONE_JWT}"},
        status=200,
    )

    assert res.json is None
Example #37
0
class ApiTestCase(utils.TestCase):

    def setUp(self):
        super(ApiTestCase, self).setUp()

        # Mock methods
        db._now = MagicMock(return_value=NOW)   # pylint: disable=W0212
        uuid.uuid4 = MagicMock(return_value=UUID)

        self.db = utils.db_init()
        self.server = api.ComputeApiServer()
        self.app = TestApp(self.server.app)

    def tearDown(self):
        super(ApiTestCase, self).tearDown()

    def test_keypair_add_new(self):
        resp = self.app.post('/v1.1/1234/os-keypairs',
                             json.dumps(KEYPAIR_ADD_NEW_REQ), status=200)
        jresp = json.loads(resp.body)

        self.assertEqual(jresp['keypair']['name'],
                         KEYPAIR_ADD_NEW_REQ['keypair']['name'])
        for key in KEYPAIR_ADD_NEW_RESP_KEYS:
            self.assertEqual(key in jresp['keypair'], True)
        for key in jresp['keypair']:
            self.assertEqual(key in KEYPAIR_ADD_NEW_RESP_KEYS, True)

    def test_keypair_add(self):
        resp = self.app.post('/v1.1/1234/os-keypairs',
                             json.dumps(KEYPAIR_ADD_REQ), status=200)

        self.assertEqual(json.loads(resp.body), KEYPAIR_ADD_RESP)

    def test_keypair_list(self):
        self.app.post('/v1.1/1234/os-keypairs', json.dumps(KEYPAIR_ADD_REQ),
                      status=200)
        resp = self.app.get('/v1.1/1234/os-keypairs', status=200)

        self.assertEqual(json.loads(resp.body), KEYPAIR_LIST_RESP)

    def test_keypair_show(self):
        self.app.post('/v1.1/1234/os-keypairs', json.dumps(KEYPAIR_ADD_REQ),
                      status=200)
        resp = self.app.get('/v1.1/1234/os-keypairs/Test%20key', status=200)

        self.assertEqual(json.loads(resp.body), KEYPAIR_SHOW_RESP)

    def test_keypair_delete(self):
        self.app.post('/v1.1/1234/os-keypairs', json.dumps(KEYPAIR_ADD_REQ),
                      status=200)
        resp = self.app.delete('/v1.1/1234/os-keypairs/Test%20key', status=200)

        self.assertEqual(resp.body, '')
        resp = self.app.get('/v1.1/1234/os-keypairs', status=200)
        self.assertEqual(json.loads(resp.body), {'keypairs': []})
Example #38
0
    def test_method_not_allowed_delete(self):
        class ThingsController(RestController):
            @expose()
            def get_one(self):
                return dict()

        app = TestApp(make_app(ThingsController()))
        r = app.delete('/123', status=405)
        assert r.status_int == 405
        assert r.headers['Allow'] == 'GET'
Example #39
0
def test_delete_group():
    c = Client(App())

    response = c.post(
        "/login",
        json.dumps({
            "email": "*****@*****.**",
            "password": "******"
        }))

    headers = {"Authorization": response.headers["Authorization"]}

    with db_session:
        assert Group.exists(name="Moderator")

    c.delete("/groups/2", headers=headers)

    with db_session:
        assert not Group.exists(name="Moderator")
Example #40
0
class TestIntegrated(unittest.TestCase):
    def setUp(self):
        self.app = TestApp(application)

    def test_columns(self):
        self.assertEqual(['age', 'id', 'name'], User.columns())

    def _create(self, name=None, age=None):
        return self.app.post_json(build_url(), {'age': age, 'name': name})

    def test_api(self):
        # test post create
        resp = self._create(name='felipe', age=22)
        result = resp.json['result']

        self.assertEqual(result['name'], 'felipe')
        self.assertEqual(result['age'], 22)
        self.assertIsNotNone(result['id'])
        id_created = str(result['id'])

        self._create(name='john', age=26)

        # test get all
        resp = self.app.get(build_url())
        result = resp.json['result']

        names = ['felipe', 'john']
        for user in result:
            self.assertTrue(user['name'] in names)
            self.assertIsNotNone(user['id'])

        # test get by id
        resp = self.app.get(build_url(id_created))
        result = resp.json['result']
        self.assertEqual('felipe', result['name'])
        self.assertEqual(22, result['age'])

        # test update
        resp = self.app.put_json(build_url(id_created),
                                 {'name': 'felipe volpone'})
        self.assertEqual(200, resp.status_int)

        resp = self.app.get(build_url(id_created))
        result = resp.json['result']
        self.assertEqual('felipe volpone', result['name'])
        self.assertEqual(22, result['age'])
        self.assertEqual(int(id_created), result['id'])

        # test delete
        resp = self.app.delete(build_url(id_created))
        self.assertEqual(200, resp.status_int)

        # test get
        resp = self.app.get(build_url(id_created), expect_errors=True)
        self.assertEqual(404, resp.status_int)
Example #41
0
def test_web_basic():
    """The web basic test
    """
    class TestService(Service):
        """The test service
        """
        @get('/test/get')
        @post('/test/post')
        @put('/test/put')
        @delete('/test/delete')
        @head('/test/head')
        @patch('/test/patch')
        @options('/test/options')
        @endpoint()
        def test(self):
            """Test
            """
            return 'OK'

        @get('/test2')
        @endpoint()
        def test2(self, param):
            """Test 2
            """
            return 'OK'

    adapter = WebAdapter()
    server = Server([ TestService() ], [ adapter ])
    server.start()
    # Test
    app = TestApp(adapter)
    rsp = app.get('/test', expect_errors = True)
    assert rsp.status_int == 404
    rsp = app.get('/test/get')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.post('/test/post')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.put('/test/put')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.delete('/test/delete')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.head('/test/head')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain'
    rsp = app.patch('/test/patch')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.options('/test/options')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    # Too many parameters
    rsp = app.get('/test/get?a=1', expect_errors = True)
    assert rsp.status_int == 400
    # Lack of parameters
    rsp = app.get('/test2', expect_errors = True)
    assert rsp.status_int == 400
    rsp = app.get('/test2?param=1')
    assert rsp.status_int == 200 and rsp.text == 'OK'
Example #42
0
class TestIntegrated(unittest.TestCase):

    def setUp(self):
        self.app = TestApp(application)

    def test_columns(self):
        self.assertEqual(['age', 'id', 'name'], User.columns())

    def _create(self, name=None, age=None):
        return self.app.post_json(build_url(), {'age': age, 'name': name})

    def test_api(self):
        # test post create
        resp = self._create(name='felipe', age=22)
        result = resp.json['result']

        self.assertEqual(result['name'], 'felipe')
        self.assertEqual(result['age'], 22)
        self.assertIsNotNone(result['id'])
        id_created = str(result['id'])

        self._create(name='john', age=26)

        # test get all
        resp = self.app.get(build_url())
        result = resp.json['result']
        self.assertEqual(result[0]['name'], 'felipe')
        self.assertEqual(result[0]['age'], 22)
        self.assertIsNotNone(result[0]['id'])
        self.assertEqual(result[1]['name'], 'john')

        # test get by id
        resp = self.app.get(build_url(id_created))
        result = resp.json['result']
        self.assertEqual('felipe', result['name'])
        self.assertEqual(22, result['age'])

        # test update
        resp = self.app.put_json(build_url(id_created), {'name': 'felipe volpone'})
        self.assertEqual(200, resp.status_int)

        resp = self.app.get(build_url(id_created))
        result = resp.json['result']
        self.assertEqual('felipe volpone', result['name'])
        self.assertEqual(22, result['age'])
        self.assertEqual(int(id_created), result['id'])

        # test delete
        resp = self.app.delete(build_url(id_created))
        self.assertEqual(200, resp.status_int)

        # test get
        resp = self.app.get(build_url(id_created), expect_errors=True)
        self.assertEqual(404, resp.status_int)
Example #43
0
    def test_method_not_allowed_delete(self):
        class ThingsController(RestController):

            @expose()
            def get_one(self):
                return dict()

        app = TestApp(make_app(ThingsController()))
        r = app.delete('/123', status=405)
        assert r.status_int == 405
        assert r.headers['Allow'] == 'GET'
class SGDFunctionalTests(unittest.TestCase):
    def setUp(self):
        self.tmpfilename = "tmpfile.txt"
        self.tmpfilepath = os.path.join(tempfile.gettempdir(), self.tmpfilename)
        with open(self.tmpfilepath, "wb") as f:
            f.write("Upload me and delete me!")

        from src import main

        settings = {
            "pyramid.includes": ["pyramid_celery", "pyramid_redis_sessions", "pyramid_jinja2"],
            "jinja2.directories": "../templates",
            "redis.sessions.secret": "my_session_secret_for_testing_only",
            "redis.session.timeout": 30,
        }
        app = main({"__file__": "development.ini"}, **settings)

        self.testapp = TestApp(app)

    def tearDown(self):
        if os.path.isfile(self.tmpfilepath):
            os.remove(self.tmpfilepath)

    # def test_home(self):
    #     res = self.testapp.get('/')
    #     self.assertEqual(res.status, '200 OK')
    #     self.assertIn(b'<h1>SGD File Uploader</h1>', res.body)

    # @mock_s3
    # def test_upload(self):
    #     upload = MockFileStorage()
    #     upload.file = StringIO.StringIO('upload me!')
    #     upload.filename = 'file.txt'

    #     TODO: insert csrf and authentication in the session.

    #     res = self.testapp.post('/upload', upload_files=[('file', self.tmpfilepath)])

    #     self.assertEqual(res.status, '200 OK')

    @mock.patch("src.views.curator_or_none")  # TODO: setup testing DB
    @mock.patch("oauth2client.client.verify_id_token")
    @mock.patch("src.views.check_csrf_token", return_value=True)  # TODO: insert csrf in the session
    def test_sign_in(self, csrf_token, token_validator, curator_or_none):
        token_validator.return_value = {"iss": "accounts.google.com", "email": "*****@*****.**"}
        curator_or_none.return_value = factory.DbuserFactory.build()

        res = self.testapp.post("/signin", {"google_token": "abcdef"}, {"X-CSRF-Token": "csrf"})
        self.assertEqual(res.status, "200 OK")

    def test_sign_out(self):
        res = self.testapp.delete("/signout")
        self.assertEqual(res.status, "200 OK")
Example #45
0
    def delete(self,
               wsgi: webtest.TestApp,
               uri,
               token=None,
               headers=None,
               **kwargs):
        if headers is None:
            headers = {}
        if token is not None:
            headers['Authorization'] = 'Bearer ' + token

        return wsgi.delete(url=uri, headers=headers, **kwargs)
Example #46
0
class FunctionalTests(fake_filesystem_unittest.TestCase):
    def setUp(self):
        from website_editor import main

        settings = {'posts_dir_path': '/path/to/posts'}
        app = main({}, **settings)

        from webtest import TestApp
        self.testapp = TestApp(app)

        self.setUpPyfakefs()
        self.fs.create_dir(settings['posts_dir_path'])

    def test_post_lifecycle(self):
        res = self.testapp.post_json('/api/posts', {
            'file_path': '/path/to/posts/1.md',
            'post_with_metadata': 'Hi!'
        })

        self.assertEqual(200, res.status_int)

        res = self.testapp.get('/api/posts')

        self.assertEqual(200, res.status_int)
        self.assertEqual(1, len(res.json_body))

        post_id = res.json_body['posts'][0]['post_id']

        res = self.testapp.put_json('/api/posts/%d' % post_id, {
            'file_path': '/path/to/posts/1.md',
            'post_with_metadata': 'Hola!'
        })

        self.assertEqual(200, res.status_int)

        res = self.testapp.get('/api/posts/%d' % post_id)

        self.assertEqual(200, res.status_int)
        self.assertEqual(
            {
                'file_path': '/path/to/posts/1.md',
                'post_with_metadata': 'Hola!',
                'post_id': 0
            }, res.json_body)

        res = self.testapp.delete('/api/posts/%d' % post_id)

        self.assertEqual(200, res.status_int)

        res = self.testapp.get('/api/posts/%d' % post_id, status=404)

        self.assertEqual(404, res.status_int)
def test_delete_todo():
    c = Client(App())

    response = c.delete('/todos/2')
    todo_list = {"todos": [
        {"@id": "http://localhost/todos/0",
         "title": "Code", "completed": True},
        {"@id": "http://localhost/todos/1",
         "title": "Test", "completed": False},
        {"@id": "http://localhost/todos/3",
         "title": "Release", "completed": False}
    ]}
    assert response.json == todo_list
Example #48
0
def test_delete_animal():
    c = Client(App())

    response = c.delete('/animals/2')
    zoo = {"animals": [
        {"@id": "http://localhost/animals/0",
         "name": "Bob", "species": "snake"},
        {"@id": "http://localhost/animals/1",
         "name": "Fred", "species": "snake"},
        {"@id": "http://localhost/animals/3",
         "name": "Kate", "species": "tiger"}
    ]}
    assert response.json == zoo
Example #49
0
class Borrado(TestCase):

    @classmethod
    def setUpClass(self):

        # Cargamos los datos
        entidad = cargar_datos('grupo')[0]
        self.uid = entidad['cn']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)
        
        self.testapp.post_json('/grupos', status=201, params=self.datos, headers=self.token)
    
    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/grupos/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/grupos/' + self.uid, status=200, headers=self.token)
    
    def test_borrado(self):
        res = self.testapp.delete('/grupos/' + self.uid, status=200, headers=self.token)
    
    def test_borrado_noexistente(self):
        uid = "fitzcarraldo"
        res = self.testapp.delete('/grupos/' + uid, status=404, headers=self.token)
    
    def test_borrado_noauth(self):
        res = self.testapp.delete('/grupos/' + self.uid, status=403)
Example #50
0
class DeleteTipoFase(unittest.TestCase):
    """
    @summary: Testea la desasociacion entre un tipo de item y una fase.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = ProyectoDAO(None)
        rol_dao = RolFinalDAO(None)
        autor = rol_dao.get_by_id(1)
        lider = rol_dao.get_by_id(1)
        nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba",
                                  "hoy", "hoy")
        dao.crear(nuevo_proyecto)

        dao = FaseDAO(None)
        nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba",
                          "0")
        dao.crear(nueva_fase)

        dao = TipoItemDAO(None)
        tipo = dao.get_by_id(1)

        dao = TipoFaseDAO(None)
        nuevo_tipo_fase = TipoFase(nueva_fase, tipo)
        dao.crear(nuevo_tipo_fase)

        direccion = '/tipofase/' + str(nuevo_tipo_fase.id)
        tipo_fase = {
            "id": nuevo_tipo_fase.id,
            "_tipo": 2,
            "tipo_nombre": "Tipo 1",
            "_fase": 70
        }
        res = self.testapp.delete(direccion, params=json.dumps(tipo_fase))
        print "Testeando eliminar asociacion entre tipo de item y fase"
        self.failUnless('sucess' in res.body)
Example #51
0
class DeleteEsquemas(unittest.TestCase):
    """
    @summary: Testea la eliminacion de esquemas.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = ProyectoDAO(None)
        rol_dao = RolFinalDAO(None)
        autor = rol_dao.get_by_id(1)
        lider = rol_dao.get_by_id(1)
        nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba",
                                  "hoy", "hoy")
        dao.crear(nuevo_proyecto)

        dao = FaseDAO(None)
        nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba",
                          "0")
        dao.crear(nueva_fase)

        esquemaDao = EsquemaDAO(None)
        nueva_entidad = Esquema("Esquema", "_descripcion", "_etiqueta",
                                "_color", nueva_fase.id)
        esquemaDao.crear(nueva_entidad)

        direccion = '/esquemas/' + str(nueva_entidad.id)
        esquema = {
            "id": nueva_entidad.id,
            "_nombre": "Esquema Prueba",
            "_descripcion": "Prueba",
            "_etiqueta": "Esquema",
            "_color": "0",
            "_fase_id": nueva_fase.id
        }
        res = self.testapp.delete(direccion, params=json.dumps(esquema))
        print "Testeando eliminar esquemas"
        self.failUnless('sucess' in res.body)
Example #52
0
def test_view_images(town_app):

    client = Client(town_app)

    assert client.get('/bilder', expect_errors=True).status_code == 403

    login_page = client.get('/login')
    login_page.form.set('email', '*****@*****.**')
    login_page.form.set('password', 'hunter2')
    login_page.form.submit()

    images_page = client.get('/bilder')

    assert "Noch keine Bilder hochgeladen" in images_page

    images_page.form['file'] = Upload('Test.txt', b'File content')
    assert images_page.form.submit(expect_errors=True).status_code == 415

    images_page.form['file'] = Upload('Test.jpg', utils.create_image().read())
    images_page = images_page.form.submit().follow()

    assert "Noch keine Bilder hochgeladen" not in images_page

    name = images_page.pyquery('img').attr('src').split('/')[-1]

    # thumbnails are created on the fly
    assert town_app.filestorage.exists('images/' + name)
    assert not town_app.filestorage.exists('images/thumbnails' + name)
    client.get('/thumbnails/' + name)
    assert town_app.filestorage.exists('images/thumbnails/' + name)

    # thumbnails are deleted with the image
    delete_link = images_page.pyquery('a.delete').attr('ic-delete-from')
    client.delete(delete_link)
    assert not town_app.filestorage.exists('images/' + name)
    assert not town_app.filestorage.exists('images/thumbnails/' + name)
Example #53
0
class DeleteAtributoFase(unittest.TestCase):
    """
    @summary: Testea la eliminacion de atributos particulares de una fase.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = ProyectoDAO(None)
        rol_dao = RolFinalDAO(None)
        autor = rol_dao.get_by_id(1)
        lider = rol_dao.get_by_id(1)
        nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba",
                                  "hoy", "hoy")
        dao.crear(nuevo_proyecto)

        dao = FaseDAO(None)
        nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba",
                          "0")
        dao.crear(nueva_fase)

        dao = AtributoFaseDAO(None)
        nuevo_atributo = AtributoFase("Atributo de prueba", nueva_fase,
                                      "Prueba", "100")
        dao.crear(nuevo_atributo)

        direccion = '/atributofase/' + str(nuevo_atributo.id)
        atributo = {
            "_nombre": "Atributo 1",
            "id": nuevo_atributo.id,
            "_fase_id": nueva_fase.id,
            "_descripcion": "Prueba",
            "_valor": "100"
        }
        res = self.testapp.delete(direccion, params=json.dumps(atributo))
        print "Testeando eliminar atributo de fase"
        self.failUnless('sucess' in res.body)
Example #54
0
class ApiRoutesTestCase(unittest.TestCase):

    def setUp(self):
        self.app = TestApp(api.app)

    def test_should_post_to_add_and_get_a_201(self):
        response = self.app.post("/resources")
        self.assertEqual(201, response.status_code)

    def test_should_post_to_bind_passing_a_name_and_receive_201(self):
        response = self.app.post("/resources/myappservice")
        self.assertEqual(201, response.status_code)

    def test_should_delete_to_unbind_and_receive_200(self):
        response = self.app.delete("/resources/myappservice")
        self.assertEqual(200, response.status_code)
Example #55
0
class DeleteFases(unittest.TestCase):
    """
    @summary: Testea la eliminacion de fases de un proyecto.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = ProyectoDAO(None)
        rol_dao = RolFinalDAO(None)
        autor = rol_dao.get_by_id(1)
        lider = rol_dao.get_by_id(1)
        nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba",
                                  "hoy", "hoy")
        dao.crear(nuevo_proyecto)

        dao = FaseDAO(None)
        nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba",
                          "0")
        dao.crear(nueva_fase)

        direccion = '/fases/' + str(nueva_fase.id)
        fase = {
            "_nombre": "Fase 3",
            "id": nueva_fase.id,
            "_proyecto_id": 69,
            "_orden": 3,
            "_comentario": "Prueba",
            "_estado": "Pendiente",
            "_color": "008080"
        }
        res = self.testapp.delete(direccion, params=json.dumps(fase))
        print "Testeando eliminar fases"
        self.failUnless('sucess' in res.body)
Example #56
0
class ClientTest(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(ClientTest, self).__init__(*args, **kwargs)
        app.debug = True
        self.client = TestApp(app)

    def get(self, url, params=None, headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, xhr=False):
        self.resp = self.client.get(url, params, headers, extra_environ, status, expect_errors, xhr)
        return self.resp

    def post(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False):
        self.resp = self.client.post(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr)
        return self.resp

    def put(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False):
        self.resp = self.client.put(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr)
        return self.resp
    def delete(self,url ,params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, content_type=None, xhr=False):
        self.resp = self.client.delete(url, params, headers, extra_environ, status, expect_errors, content_type, xhr)
Example #57
0
class DeleteProyectos(unittest.TestCase):
    """
    @summary: Testea eliminacion de proyectos.                         
    """
    def setUp(self):
        from yapp import main
        settings = {
            'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp'
        }
        app = main({}, **settings)
        from webtest import TestApp
        self.testapp = TestApp(app)

    def tearDown(self):
        del self.testapp
        from yapp.models import DBSession
        DBSession.remove()

    def test_it(self):
        dao = ProyectoDAO(None)
        rol_dao = RolFinalDAO(None)
        autor = rol_dao.get_by_id(1)
        lider = rol_dao.get_by_id(1)
        nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba",
                                  "hoy", "hoy")
        dao.crear(nuevo_proyecto)
        direccion = '/deleteProyectos/' + str(nuevo_proyecto.id)
        proyecto = {
            "_nombre": "Prueba",
            "_autor": 1,
            "_autor_id": 1,
            "id": nuevo_proyecto.id,
            "_prioridad": 1,
            "_estado": "Prueba",
            "_lider_id": 1,
            "lider_nombre": 1,
            "_nota": "Prueba",
            "_fecha_creacion": "2012-06-18, 3:46 pm",
            "_fecha_modificacion": "2012-06-18, 3:46 pm"
        }
        res = self.testapp.delete(direccion, params=json.dumps(proyecto))
        print "Testeando eliminar proyectos"
        self.failUnless('sucess' in res.body)
Example #58
0
    def test_rest_with_utf8_uri(self):

        class FooController(RestController):
            key = chr(0x1F330) if PY3 else unichr(0x1F330)
            data = {key: 'Success!'}

            @expose()
            def get_one(self, id_):
                return self.data[id_]

            @expose()
            def get_all(self):
                return "Hello, World!"

            @expose()
            def put(self, id_, value):
                return self.data[id_]

            @expose()
            def delete(self, id_):
                return self.data[id_]

        class RootController(RestController):
            foo = FooController()

        app = TestApp(make_app(RootController()))

        r = app.get('/foo/%F0%9F%8C%B0')
        assert r.status_int == 200
        assert r.body == b'Success!'

        r = app.put('/foo/%F0%9F%8C%B0', {'value': 'pecans'})
        assert r.status_int == 200
        assert r.body == b'Success!'

        r = app.delete('/foo/%F0%9F%8C%B0')
        assert r.status_int == 200
        assert r.body == b'Success!'

        r = app.get('/foo/')
        assert r.status_int == 200
        assert r.body == b'Hello, World!'