当前位置: 首页>>代码示例>>Python>>正文


Python TestApp.patch方法代码示例

本文整理汇总了Python中webtest.TestApp.patch方法的典型用法代码示例。如果您正苦于以下问题:Python TestApp.patch方法的具体用法?Python TestApp.patch怎么用?Python TestApp.patch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在webtest.TestApp的用法示例。


在下文中一共展示了TestApp.patch方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_singular_resource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
    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)
开发者ID:mbijon,项目名称:nefertari,代码行数:54,代码来源:test_resource.py

示例2: test_web_basic

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
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'
开发者ID:penfree,项目名称:pyunified-rpc,代码行数:57,代码来源:test_web.py

示例3: TestIntegration

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
class TestIntegration(unittest.TestCase):

    def setUp(self):
        app = Application('tangled.web.tests:test.ini')
        app.mount_resource('user', UserResource, '/users/<id>')
        self.app = TestApp(app)
        self._original_data = copy.deepcopy(Users.data)

    def tearDown(self):
        Users.data = self._original_data

    def test_get(self):
        self.assertEqual(Users.get(1)['name'], 'Alice')
        response = self.app.get('/users/1')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['name'], 'Alice')
        self.assertEqual(Users.get(1)['name'], 'Alice')

    def test_put(self):
        self.assertEqual(Users.get(2)['name'], 'Bob')
        response = self.app.put('/users/2', params={'name': 'Bobby'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['name'], 'Bobby')
        self.assertEqual(Users.get(2)['name'], 'Bobby')

    def test_patch(self):
        self.assertEqual(Users.get(2)['name'], 'Bob')
        response = self.app.patch('/users/2', params={'name': 'Bobby'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['name'], 'Bobby')
        self.assertEqual(Users.get(2)['name'], 'Bobby')

    def test_patch_json(self):
        self.assertEqual(Users.get(2)['name'], 'Bob')
        response = self.app.patch_json('/users/2', params={'name': 'Bobby'})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['name'], 'Bobby')
        self.assertEqual(Users.get(2)['name'], 'Bobby')
开发者ID:TangledWeb,项目名称:tangled.web,代码行数:40,代码来源:test_integration.py

示例4: KuleTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
class KuleTests(unittest.TestCase):
    """
    Functionality tests for kule.
    """
    def setUp(self):
        self.kule = Kule(database="kule_test",
                         collections=["documents"])
        self.app = TestApp(self.kule.get_bottle_app())
        self.collection = self.kule.get_collection("documents")

    def tearDown(self):
        self.collection.remove()

    def test_empty_response(self):
        response = self.app.get("/documents")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json,
                         {'meta': {
                             'total_count': 0,
                             'limit': 20,
                             'offset': 0},
                          'objects': []})

    def test_get_list(self):
        self.collection.insert({"foo": "bar"})
        response = self.app.get("/documents")
        self.assertEqual(response.status_code, 200)
        objects = response.json.get("objects")
        meta = response.json.get("meta")
        self.assertEqual(1, len(objects))
        self.assertEqual(1, meta.get("total_count"))
        record = first(objects)
        self.assertEqual(record.get("foo"), "bar")

    def test_post_list(self):
        response = self.app.post("/documents", json.dumps({"foo": "bar"}),
                                 content_type="application/json")
        self.assertEqual(201, response.status_code)
        object_id = response.json.get("_id")
        query = {"_id": bson.ObjectId(object_id)}
        self.assertEqual(1, self.collection.find(query).count())
        record = self.collection.find_one(query)
        self.assertEqual(record.get("foo"), "bar")

    def test_get_detail(self):
        object_id = str(self.collection.insert({"foo": "bar"}))
        response = self.app.get("/documents/%s" % object_id)
        self.assertEqual(200, response.status_code)
        self.assertEqual(response.json, {'_id': object_id,
                                         'foo': 'bar'})

    def test_put_detail(self):
        object_id = self.collection.insert({"foo": "bar"})
        response = self.app.put("/documents/%s" % object_id,
                                json.dumps({"bar": "foo"}),
                                content_type="application/json")
        self.assertEqual(response.status_code, 202)
        record = self.collection.find_one({"_id": object_id})
        self.assertEqual(record, {'_id': object_id,
                                  'bar': 'foo'})

    def test_patch_detail(self):
        object_id = self.collection.insert({"foo": "bar"})
        response = self.app.patch("/documents/%s" % object_id,
                                  json.dumps({"bar": "foo"}),
                                  content_type="application/json")
        self.assertEqual(response.status_code, 202)
        record = self.collection.find_one({"_id": object_id})
        self.assertEqual(record, {'_id': object_id,
                                  'foo': 'bar',
                                  'bar': 'foo'})

    def test_delete_detail(self):
        object_id = self.collection.insert({"foo": "bar"})
        response = self.app.delete("/documents/%s" % object_id)
        self.assertEqual(response.status_code, 204)
        self.assertEqual(0, self.collection.find(
            {"_id": object_id}).count())

    def test_magical_methods(self):
        class MyKule(Kule):
            def get_documents_list(self):
                return {"foo": "bar"}
        kule = MyKule(database="kule_test", collections=["documents"])
        app = TestApp(kule.get_bottle_app())
        self.assertEqual(app.get("/documents").json, {"foo": "bar"})

    def test_bundler(self):
        class MyKule(Kule):
            def build_documents_bundle(self, document):
                return {"_title": document.get("title")}
        kule = MyKule(database="kule_test", collections=["documents"])
        app = TestApp(kule.get_bottle_app())
        object_id = kule.get_collection("documents").insert({"title": "bar"})
        result = app.get("/documents/%s" % object_id).json
        self.assertEqual(result ,{"_title": "bar"})
开发者ID:Jaykul,项目名称:kule,代码行数:98,代码来源:tests.py

示例5: TestCustomPredicates

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
class TestCustomPredicates(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP
        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)
        self.config.add_route_predicate('position', employeeType)
        self.config.scan("tests.test_resource_custom_predicates")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_get_resource_predicates(self):
        # Tests for resource with name 'Supervisors'
        res = self.app.get('/company/employees?position=supervisor').json
        self.assertEqual(res[0], 'Supervisors list get')
        res = self.app.get('/company/employees/2?position=supervisor').json
        self.assertEqual(res['get'], 'Supervisors')

        # Tests for resource with name 'Topmanagers'
        res = self.app.get('/company/employees?position=topmanager').json
        self.assertEqual(res[0], 'Topmanagers list get')
        res = self.app.get('/company/employees/1?position=topmanager').json
        self.assertEqual(res['get'], 'Topmanagers')

    def test_post_resource_predicates(self):
        # Tests for resource with name 'Supervisors'
        supervisor_data = {
            'name': 'Jimmy Arrow',
            'position': 'supervisor',
            'salary': 50000
        }
        res = self.app.post('/company/employees', supervisor_data).json
        self.assertEqual(res[0], 'Supervisors list post')

        # Tests for resource with name 'Topmanagers'
        topmanager_data = {
            'name': 'Jimmy Arrow',
            'position': 'topmanager',
            'salary': 30000
        }
        res = self.app.post('/company/employees', topmanager_data).json
        self.assertEqual(res[0], 'Topmanagers list post')

    def test_patch_resource_predicates(self):
        # Tests for resource with name 'Supervisors'
        res = self.app.patch(
            '/company/employees/2?position=supervisor',
            {'salary': 1001}
        ).json
        self.assertEqual(res['patch'], 'Supervisors')

        # Tests for resource with name 'Topmanagers'
        res = self.app.patch(
            '/company/employees/1?position=topmanager',
            {'salary': 2002}
        ).json
        self.assertEqual(res['patch'], 'Topmanagers')

    def test_put_resource_predicates(self):
        # Tests for resource with name 'Supervisors'
        supervisor_data = {
            'position': 'supervisor',
            'salary': 53000
        }
        res = self.app.put('/company/employees/2', supervisor_data).json
        self.assertEqual(res['put'], 'Supervisors')

        # Tests for resource with name 'Topmanagers'
        topmanager_data = {
            'position': 'topmanager',
            'salary': 33000
        }
        res = self.app.put('/company/employees/1', topmanager_data).json
        self.assertEqual(res['put'], 'Topmanagers')
开发者ID:joesteeve,项目名称:cornice,代码行数:84,代码来源:test_resource_custom_predicates.py

示例6: TestAdminAPI

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
class TestAdminAPI(unittest.TestCase):
    """Tests API functions associated with VM actions.
       Note that all tests are in-process, we don't actually start a HTTP server,
       but we do communicate HTTP requests and responses.
       Outside of setUp, all calls to the database should be via the HTTP API.
    """
    def setUp(self):
        """Launch pserve using webtest with test settings"""
        self.appconf = get_app(test_ini)
        self.app = TestApp(self.appconf)

        #This seems to be how we suppress cookies being remembered.
        #All auth via BasicAuth - never return the session cookie.
        self.app.cookiejar.set_policy(DefaultCookiePolicy(allowed_domains=[]))

        # This sets global var "engine" - in the case of SQLite this is a fresh RAM
        # DB each time.  If we only did this on class instantiation the database would
        # be dirty and one test could influence another.
        # TODO - add a test that tests this.
        server.choose_engine("SQLite")

        # Punch in new administrator account with direct server call
        # This will implicitly generate the tables.
        user_id = server.create_user("administrators", "administrator", "administrator", "administrator")
        #server.touch_to_add_user_group("administrator", "administrators")
        server.touch_to_add_password(user_id, "adminpass")

        self.app.authorization = ('Basic', ('administrator', 'adminpass'))

    """Unauthenticated API functions."""

    def test_home_view(self):
        """ Home view should respond with 200 OK, as anyone can call it. """
        response = self.app.get('/', status=200)

    """Admin API functions.

    The admin functions in the API are primarily used by system utilities.
    Creating a user and password, and validating against the database in
    order to receive an access token, are prerequisites for using functions
    in later sections of the API. These can only be called by an
    administrator."""

    def test_create_user(self):
        """ Creating a user should respond with 200 OK.
        Retrieving the user should respond likewise. """

        newuser = { 'type': 'users',
                    'handle': '[email protected]',
                    'name': 'Test User',
                    'username':'ignored'} #Should be ignored!

        self.app.put('/users/testuser', newuser, status=200)

        newuser2 = self.app.get('/users/testuser', status=200).json

        #Fold real user name into dict and remove type
        newuser['username'] = 'testuser'
        del(newuser['type'])

        #User id should be 1, but we'll ignore it.  Ditto credits.
        del(newuser2['id'])
        del(newuser2['credits'])

        self.assertEqual(newuser2, newuser)

        #There should be no user named 'ignored'
        self.app.get('/users/ignored', status=404)

    def test_get_my_details(self):
        """As an admin, fetching /users/<me> should produce exactly the
           same result as fetching /user
        """

        r1 = self.app.get('/users/administrator')
        r2 = self.app.get('/user')

        self.assertEqual(r1.json, r2.json)

    #!! Not implemented.
    @unittest.skip
    def test_update_user(self):
        """ Updating a user. Retrieve details. The results should reflect the
            change.
        """
        self.create_user('testuser')

        self.app.patch(           '/users/testuser',
                                  {'type': 'users',
                                  'handle': '[email protected]',
                                  'name': 'Test User Updated',
                                  'username':'testuser'})
        response = self.app.get('/users/testuser?actor_id=testuser')

        self.assertEqual(response.json['name'], 'Test User Updated')

    #!! Not implemented.
    @unittest.skip
    def test_update_self(self):
        """ Updating myself. Retrieve details. The results should reflect the
#.........这里部分代码省略.........
开发者ID:cedadev,项目名称:eos-db,代码行数:103,代码来源:test_administrator_api.py

示例7: model_tests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]

#.........这里部分代码省略.........
            'read_only': False,
            'widgets_allowed': True
        }, status=201)
        resp = response.json
        print "Created user:", resp['_id']

        # Get and control and patch
        response = self.app.get('/user?where={"name":"user2"}')
        resp = response.json
        assert resp['_meta']['total'] > 0
        item = resp['_items'][0]
        print item
        assert item['name'] == 'user2'
        assert item['friendly_name'] == 'Friendly name'
        assert item['password']

        # Login new user
        # -----------------------------
        response = self.app.post('/logout')
        response.mustcontain('ok')
        response = self.app.post_json('/login', {'username': 'user2', 'password': 'password'})
        assert response.json['token']

        # Login admin
        # -----------------------------
        response = self.app.post_json('/login', {'username': 'admin', 'password': 'admin'})
        assert response.json['token']

        response = self.app.get('/user?where={"name":"user2"}')
        resp = response.json
        assert resp['_meta']['total'] > 0
        item = resp['_items'][0]

        response = self.app.patch('/user/'+item['_id'], {'friendly_name':'Patched friendly name'}, headers=[('If-Match', str(item['_etag']))], status=200)
        resp = response.json
        assert resp['_id'] == item['_id']

        response = self.app.get('/user/'+resp['_id'])
        resp = response.json
        item = resp
        assert item['friendly_name'] == 'Patched friendly name'

        # Change password
        response = self.app.patch('/user/'+item['_id'], {'password':'new_password'}, headers=[('If-Match', str(item['_etag']))], status=200)
        resp = response.json
        assert resp['_id'] == item['_id']

        # Login new user
        # -----------------------------
        response = self.app.post('/logout')
        response.mustcontain('ok')
        response = self.app.post_json('/login', {'username': 'user2', 'password': 'new_password'})
        assert response.json['token']

        # Login admin
        # -----------------------------
        response = self.app.post_json('/login', {'username': 'admin', 'password': 'admin'})
        assert response.json['token']

        response = self.app.get('/user?where={"name":"user2"}')
        resp = response.json
        assert resp['_meta']['total'] > 0
        item = resp['_items'][0]

    def test_4_create_userservices(self):
开发者ID:IPM-France,项目名称:applications-backend,代码行数:69,代码来源:test_web.py

示例8: ViewTest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]

#.........这里部分代码省略.........
            ('url', 'http://howies.com/products/milk/5'),
            ('product_title',
             u'Молоко Красная Цена у/паст. 1% 1л'.encode('utf-8')),
            ('merchant_title', "Howie's grocery"),
            ('reporter_name', 'Jack'),

            ('price_value', 67.1),
            ('url', 'http://howies.com/products/milk/6'),
            ('product_title',
             u'Волшебный Элексир Красная Цена у/паст. 1% 1л'.encode('utf-8')),
            ('merchant_title', "Howie's grocery"),
            ('reporter_name', 'Jack'),
            ('date_time', '2014-12-1')
        ]
        res = self.testapp.post('/reports', data, status=400)
        self.assertIn('Bad multidict: value counts not equal', res.body)

    def test_report_delete(self):
        res = self.testapp.delete('/reports/{}'.format(self.report_key),
                                  status=200)
        self.assertIn('deleted_report_key', res.body)
        self.testapp.get('/reports/{}'.format(self.report_key), status=404)

    def test_page_get(self):
        res = self.testapp.get('/pages/about', status=200)
        self.assertIn(u'О проекте', res.text)

    def test_page_post(self):
        res = self.testapp.post('/pages', [('slug', 'test')], status=200)
        self.assertIn('new_page', res.body)

        self.testapp.get('/pages/test', status=404)

    def test_merchant_patch(self):
        res = self.testapp.patch(
            u"/merchants/Московский магазин".encode('utf-8'),
            [('title', 'Fred & Co.')],
            status=200)
        self.assertEqual('Fred & Co.', res.json_body['title'])
        self.testapp.get(
            u"/merchants/Московский магазин".encode('utf-8'),
            status=404)
        res = self.testapp.get("/merchants/Fred & Co.", status=200)
        self.assertEqual('Fred & Co.', res.json_body['title'])

    def test_merchants_get(self):
        res = self.testapp.get('/merchants', status=200)
        self.assertIn(u"Московский магазин", res.json_body)

    def test_product_chart_data(self):
        data = [
            ('price_value', 55.6),
            ('url', 'http://howies.com/products/milk/4'),
            ('product_title',
             u'Молоко Deli Milk 1L'.encode('utf-8')),
            ('merchant_title', "Howie's grocery"),
            ('reporter_name', 'Jack'),
            ('date_time', TWO_WEEKS_AGO),

            ('price_value', 54.8),
            ('url', 'http://eddies.com/products/milk/4'),
            ('product_title',
             u'Молоко Deli Milk 1L'.encode('utf-8')),
            ('merchant_title', "Eddie's grocery"),
            ('reporter_name', 'Jack'),
            ('date_time', TWO_WEEKS_AGO),
开发者ID:gitter-badger,项目名称:price_watch,代码行数:70,代码来源:functional_tests.py

示例9: DwarfTestCase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
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_versions(self):
        resp = self.app.get('/image', status=300)
        self.assertEqual(json.loads(resp.body), list_versions_resp())

    def test_list_images(self):
        # Preload test images
        self.create_image(image1)
        self.create_image(image2)

        resp = self.app.get('/image/v2/images', status=200)
        self.assertEqual(json.loads(resp.body),
                         list_images_resp([image1, image2]))

    def test_show_image(self):
        # Preload a test image
        self.create_image(image1)

        resp = self.app.get('/image/v2/images/%s' % image1['id'], status=200)
        self.assertEqual(json.loads(resp.body), show_image_resp(image1))

    def test_delete_image(self):
        # Preload a test image
        self.create_image(image1)

        resp = self.app.delete('/image/v2/images/%s' % image1['id'],
                               status=204)
        self.assertEqual(resp.body, '')
        self.assertEqual(os.path.exists('/tmp/dwarf/images/%s' % image1['id']),
                         False)

        resp = self.app.get('/image/v2/images', status=200)
        self.assertEqual(json.loads(resp.body), list_images_resp([]))

    def test_update_image(self):
        # Preload a test image
        self.create_image(image1)

        key = 'name'
        val = 'Patched test image 1'

        resp = self.app.patch('/image/v2/images/%s' % image1['id'],
                              params=json.dumps([{'op': 'replace',
                                                  'path': '/' + key,
                                                  'value': val}]),
                              status=200)

        patched = deepcopy(image1)
        patched[key] = val
        self.assertEqual(json.loads(resp.body), update_image_resp(patched))

    def test_create_image(self):
        # Create the image in the database
        resp = self.app.post('/image/v2/images',
                             params=json.dumps(create_image_req(image1)),
                             status=201)
        self.assertEqual(json.loads(resp.body), create_image_resp(image1))

        # Upload the image data
        resp = self.app.put('/image/v2/images/%s/file' % image1['id'],
                            params=image1['data'], status=204)
        with open('/tmp/dwarf/images/%s' % image1['id'], 'r') as fh:
            self.assertEqual(fh.read(), image1['data'])

    # -------------------------------------------------------------------------
    # Additional tests for code coverage

    def test_delete_image_cc(self):
        # Preload a test image
        self.create_image(image1)
        os.unlink(image1['file'])

        resp = self.app.delete('/image/v2/images/%s' % image1['id'],
                               status=204)
        self.assertEqual(resp.body, '')
开发者ID:dtroyer,项目名称:dwarf,代码行数:86,代码来源:test_image.py

示例10: TestResourceRecognition

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch [as 别名]
class TestResourceRecognition(Test):
    def setUp(self):
        from nefertari.resource import add_resource_routes
        self.config = _create_config()
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='string'
        )
        self.config.begin()
        self.app = TestApp(self.config.make_wsgi_app())
        self.collection_path = '/messages'
        self.collection_name = 'messages'
        self.member_path = '/messages/{id}'
        self.member_name = 'message'

    def test_get_collection(self):
        self.assertEqual(self.app.get('/messages').body, six.b('index'))

    def test_get_collection_json(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    def test_get_collection_nefertari_json(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='nefertari_json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    def test_get_collection_no_renderer(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config, DummyCrudRenderedView, 'message', 'messages')
        self.assertRaises(ValueError, self.app.get, '/messages')

    def test_post_collection(self):
        result = self.app.post('/messages').body
        self.assertEqual(result, six.b('create'))

    def test_head_collection(self):
        response = self.app.head('/messages')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_get_member(self):
        result = self.app.get('/messages/1').body
        self.assertEqual(result, six.b('show'))

    def test_head_member(self):
        response = self.app.head('/messages/1')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_put_member(self):
        result = self.app.put('/messages/1').body
        self.assertEqual(result, six.b('replace'))

    def test_patch_member(self):
        result = self.app.patch('/messages/1').body
        self.assertEqual(result, six.b('update'))

    def test_delete_member(self):
        result = self.app.delete('/messages/1').body
        self.assertEqual(result, six.b('delete'))
开发者ID:mbijon,项目名称:nefertari,代码行数:82,代码来源:test_resource.py


注:本文中的webtest.TestApp.patch方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。