本文整理汇总了Python中webtest.TestApp.patch_json方法的典型用法代码示例。如果您正苦于以下问题:Python TestApp.patch_json方法的具体用法?Python TestApp.patch_json怎么用?Python TestApp.patch_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webtest.TestApp
的用法示例。
在下文中一共展示了TestApp.patch_json方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestIntegration
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch_json [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')
示例2: Modificacion
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch_json [as 别名]
class Modificacion(TestCase):
"""
NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase
TODO: Validar cambio de grupo principal
TODO: Validar cambio de estado de la cuenta
TODO: Validar cambios de grupos
TODO: Validar cambio de contraseña
TODO: Validar que tan pocas claves podemos cambiar
"""
@classmethod
def setUpClass(self):
# Cargamos los datos
entidad = cargar_datos('usuario')[2]
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_actualizacion(self):
self.datos['corpus']['title'] = "Titulador"
self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token)
res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token)
respuesta = res.json_body['mensaje'][0]['title']
datos = self.datos['corpus']['title']
self.assertEqual(respuesta, datos)
def test_actualizacion_displayName(self):
sn = "Sotomayor"
givenName = self.datos['corpus']['givenName']
displayName = givenName + " " + sn
self.datos['corpus']['sn'] = sn
self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token)
res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token)
respuesta = res.json_body['mensaje'][0]['displayName']
self.assertEqual(respuesta, displayName)
def test_corpus_faltante(self):
datos = {'cuerpo': self.datos['corpus'].copy()}
self.testapp.patch_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token)
def test_json_malformateado(self):
datos = "Mínimo esfuerzo para máximo daño"
self.testapp.patch_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token)
def test_noexistente(self):
uid = 'fitzcarraldo'
datos = {'corpus': self.datos['corpus'].copy()}
datos['corpus']['uid'] = uid
self.testapp.patch_json('/usuarios/' + uid, status=404, params=datos, headers=self.token)
def test_claves_incompletas(self):
cuerpo = self.datos['corpus'].copy()
del cuerpo['sn']
del cuerpo['givenName']
datos = {'corpus': cuerpo}
self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=datos, headers=self.token)
def test_actualizacion_noauth(self):
self.testapp.patch_json('/usuarios/' + self.uid, status=403, params=self.datos)
示例3: ApiTestCase
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch_json [as 别名]
class ApiTestCase(TestCase):
def setUp(self):
super(ApiTestCase, self).setUp()
repo_store = self.useFixture(TempDir()).path
self.useFixture(EnvironmentVariable("REPO_STORE", repo_store))
self.app = TestApp(api.main({}))
self.repo_path = uuid.uuid1().hex
self.repo_store = os.path.join(repo_store, self.repo_path)
self.repo_root = repo_store
self.commit = {'ref': 'refs/heads/master', 'message': 'test commit.'}
self.tag = {'ref': 'refs/tags/tag0', 'message': 'tag message'}
def assertReferencesEqual(self, repo, expected, observed):
self.assertEqual(
repo.lookup_reference(expected).peel().oid,
repo.lookup_reference(observed).peel().oid)
def get_ref(self, ref):
resp = self.app.get('/repo/{}/{}'.format(self.repo_path, ref))
return resp.json
def test_repo_init(self):
resp = self.app.post_json('/repo', {'repo_path': self.repo_path})
self.assertIn(self.repo_path, resp.json['repo_url'])
self.assertEqual(200, resp.status_code)
def test_repo_init_with_invalid_repo_path(self):
resp = self.app.post_json('/repo', {'repo_path': '../1234'},
expect_errors=True)
self.assertEqual(404, resp.status_code)
def test_repo_init_with_existing_repo(self):
"""Repo can be not be initialised with existing path."""
factory = RepoFactory(self.repo_store)
repo_path = os.path.basename(os.path.normpath(factory.repo_path))
resp = self.app.post_json('/repo', {'repo_path': repo_path},
expect_errors=True)
self.assertEqual(409, resp.status_code)
def test_repo_init_with_clone(self):
"""Repo can be initialised with optional clone."""
factory = RepoFactory(self.repo_store, num_commits=2)
factory.build()
new_repo_path = uuid.uuid1().hex
resp = self.app.post_json('/repo', {'repo_path': new_repo_path,
'clone_from': self.repo_path,
'clone_refs': True})
repo1_revlist = get_revlist(factory.repo)
clone_from = resp.json['repo_url'].split('/')[-1]
repo2 = open_repo(os.path.join(self.repo_root, clone_from))
repo2_revlist = get_revlist(repo2)
self.assertEqual(repo1_revlist, repo2_revlist)
self.assertEqual(200, resp.status_code)
self.assertIn(new_repo_path, resp.json['repo_url'])
def test_repo_get(self):
"""The GET method on a repository returns its properties."""
factory = RepoFactory(self.repo_store, num_branches=2, num_commits=1)
factory.build()
factory.repo.set_head('refs/heads/branch-0')
resp = self.app.get('/repo/{}'.format(self.repo_path))
self.assertEqual(200, resp.status_code)
self.assertEqual({'default_branch': 'refs/heads/branch-0'}, resp.json)
def test_repo_get_default_branch_missing(self):
"""default_branch is returned even if that branch has been deleted."""
factory = RepoFactory(self.repo_store, num_branches=2, num_commits=1)
factory.build()
factory.repo.set_head('refs/heads/branch-0')
factory.repo.lookup_reference('refs/heads/branch-0').delete()
resp = self.app.get('/repo/{}'.format(self.repo_path))
self.assertEqual(200, resp.status_code)
self.assertEqual({'default_branch': 'refs/heads/branch-0'}, resp.json)
def test_repo_patch_default_branch(self):
"""A repository's default branch ("HEAD") can be changed."""
factory = RepoFactory(self.repo_store, num_branches=2, num_commits=1)
factory.build()
factory.repo.set_head('refs/heads/branch-0')
self.assertReferencesEqual(factory.repo, 'refs/heads/branch-0', 'HEAD')
resp = self.app.patch_json(
'/repo/{}'.format(self.repo_path),
{'default_branch': 'refs/heads/branch-1'})
self.assertEqual(204, resp.status_code)
self.assertReferencesEqual(factory.repo, 'refs/heads/branch-1', 'HEAD')
def test_cross_repo_merge_diff(self):
"""Merge diff can be requested across 2 repositories."""
factory = RepoFactory(self.repo_store)
c1 = factory.add_commit('foo', 'foobar.txt')
repo2_name = uuid.uuid4().hex
factory2 = RepoFactory(
os.path.join(self.repo_root, repo2_name), clone_from=factory)
c2 = factory.add_commit('bar', 'foobar.txt', parents=[c1])
#.........这里部分代码省略.........
示例4: TestCorkscrew
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch_json [as 别名]
#.........这里部分代码省略.........
}
}
JsonAPIValidator.validate_jsonapi(request, True)
result = self.app.post_json("/articles", params=request)
self.assertEqual(result.status, "200 OK")
JsonAPIValidator.validate_content_type(result.content_type)
self.assertIsNotNone(result.json)
JsonAPIValidator.validate_jsonapi(result.json)
self.assertIn("relationships", result.json["data"])
for key, rel in result.json["data"]["relationships"].iteritems():
self.assertIn(key, ["comments", "cover", "author", "revisions"])
self.assertIn("links", rel)
self.assertIn("related", rel["links"])
self.assertIn("self", rel["links"])
def testPatch(self):
request = {
u"data": {
u"type": u"article",
u"id": u"1",
u"attributes": {
u"title": u"Changed First Entry"
}
}
}
JsonAPIValidator.validate_jsonapi(request)
result = self.app.patch_json("/articles/1", params=request)
self.assertIn(
result.status,
["202 Accepted", "200 OK", "204 No Content"]
)
if result.status == "204 No Content":
# nothing more to test
return
JsonAPIValidator.validate_content_type(result.content_type)
self.assertIsNotNone(result.json)
JsonAPIValidator.validate_jsonapi(result.json)
self.assertEqual(
result.json["data"]["attributes"]["title"],
"Changed First Entry"
)
def testDelete(self):
result = self.app.delete("/articles/1")
self.assertIn(
result.status,
["202 Accepted", "204 No Content", "200 OK"]
)
def testGetRelated(self):
result = self.app.get("/articles/1")
self.assertEqual(result.status, "200 OK")
JsonAPIValidator.validate_content_type(result.content_type)
self.assertIsNotNone(result.json)
示例5: FlaskAdapterTests
# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import patch_json [as 别名]
#.........这里部分代码省略.........
returned_time = resp.json_body['time']
# we didn't specify any other fields in the endpoint definition,
# so this one should only get the defaults
expected_fields = DateTimeResource._default_fields
self.assertExpectedFields(returned_time, expected_fields)
self.assertIn('Cache-Control', resp.headers)
self.assertEqual('max-age=3', resp.headers['Cache-Control'])
def test_successful_json_post_with_required_params(self):
# this is the same as the above post, but passes json in the
# request body, instead of x-www-form-urlencoded
resp = self.app.post_json('/api/time/parse', {'month': 2})
self.assertEqual(resp.status_code, 200)
self.assertIn('time', resp.json_body)
returned_time = resp.json_body['time']
# we didn't specify any other fields in the endpoint definition,
# so this one should only get the defaults
expected_fields = DateTimeResource._default_fields
self.assertExpectedFields(returned_time, expected_fields)
def test_unsuccessful_post_missing_required_params(self):
resp = self.app.post('/api/time/parse', status=422)
self.assertIn('error', resp.json_body)
def test_getting_with_nested_resources(self):
test_duration = 60 * 1000 # one minute in milliseconds
resp = self.app.get('/api/time/range', {'duration': test_duration})
self.assertEqual(resp.status_code, 200)
self.assertIn('range', resp.json_body)
returned_range = resp.json_body['range']
self.assertEqual(returned_range['duration_microseconds'],
test_duration * 1000)
# start has default fields
start = returned_range['start']
expected_fields = DateTimeResource._default_fields
self.assertExpectedFields(start, expected_fields)
# end has all of them
end = returned_range['end']
expected_fields = DateTimeResource._all_fields()
self.assertExpectedFields(end, expected_fields)
def test_resource(self):
# Start by resetting the resource.
# (multiple test runs from the same process will fail otherwise)
resp = self.app.post('/api/resource/reset')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.json, {'key': 'value'})
# Test creating a new resource
resp = self.app.put_json('/api/resource', {'key': 'boop'},
headers={'Content-Type': 'application/json'})
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.json, {'key': 'boop'})
# Test retrieving the resource.
resp = self.app.get('/api/resource')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.json, {'key': 'boop'})
# Test patching the resource.
# Without the correct Content-Type, we expect a 415 error.
self.assertRaises(AppError, self.app.patch_json,
'/api/resource', {'key': 'value2'})
resp = self.app.patch_json('/api/resource', {'key': 'value2'},
headers={'Content-Type': 'application/merge-patch+json'})
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.json, {'key': 'value2'})
# Test get to ensure the resource persists.
resp = self.app.get('/api/resource')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.json, {'key': 'value2'})
# A NoContentResource shouldn't have a Content-Type header (no content!)
resp = self.app.post('/api/blank')
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content_type, None)