Best Python code snippet using behave
test_document.py
Source:test_document.py
1from unittest.mock import patch2from datetime import datetime, date3from django.test import TestCase4from django.core.exceptions import ValidationError5from django.utils.timezone import make_aware6from datatypes.models import Document7class TestDocument(TestCase):8 fixtures = ["test-data-storage"]9 def setUp(self):10 super().setUp()11 self.instance = Document.objects.get(id=1)12 self.value_outcome = "0"13 self.dict_outcome = {"value": "0"}14 self.expected_items = sorted([('context', 'nested value'), ('nested', 'nested value 0'), ('value', '0')])15 self.schema = {16 "additionalProperties": False,17 "required": ["value"],18 "type": "object",19 "properties": {20 "word": {"type": "string"},21 "value": {"type": "string"},22 "language": {"type": "string"},23 "country": {"type": "string"}24 }25 }26 def test_url(self):27 # Testing standard URL's28 url = self.instance.url29 self.assertEqual(url, '/api/v1/datatypes/data/document/1/content/')30 self.instance.id = None31 try:32 url = self.instance.url33 self.fail("url property did not raise when id is not known")34 except ValueError:35 pass36 # Testing URL's with special class names37 class DocumentTest(Document):38 class Meta:39 app_label = "testing_apps"40 document_test = DocumentTest()41 document_test.id = 142 with patch("datagrowth.datatypes.documents.db.base.reverse") as reverse_mock:43 url = document_test.url44 reverse_mock.assert_called_once_with("v1:testing-apps:document-test-content", args=[1])45 @patch("datagrowth.datatypes.DocumentBase.output_from_content")46 def test_output(self, output_from_content):47 self.instance.output("$.value")48 output_from_content.assert_called_once_with(self.instance.content, "$.value")49 def test_output_from_content(self):50 results = self.instance.output_from_content(self.instance.content, "$._id")51 self.assertEqual(results, self.instance.id)52 results = self.instance.output_from_content(self.instance.content, "$.value")53 self.assertEqual(results, self.value_outcome)54 results = self.instance.output_from_content(self.instance.content, "$.value", "$.value")55 self.assertEqual(list(results), [self.value_outcome, self.value_outcome])56 results = self.instance.output_from_content(self.instance.content, ["$.value"])57 self.assertEqual(results, [self.value_outcome])58 results = self.instance.output_from_content(self.instance.content, ["$.value", "$.value"])59 self.assertEqual(list(results), [self.value_outcome, self.value_outcome])60 results = self.instance.output_from_content(self.instance.content, [])61 self.assertEqual(results, [])62 results = self.instance.output_from_content(self.instance.content, {"value": "$.value"})63 self.assertEqual(results, self.dict_outcome)64 results = self.instance.output_from_content(self.instance.content, [{"value": "$.value"}, {"value": "$.value"}])65 self.assertEqual(list(results), [self.dict_outcome, self.dict_outcome])66 results = self.instance.output_from_content(self.instance.content, {})67 self.assertEqual(results, {})68 def test_update_using_dict(self):69 created_at = self.instance.created_at70 today = date.today()71 content = self.instance.update({"value": "-1", "extra": "extra"})72 self.assertEqual(self.instance.created_at, created_at)73 self.assertNotEqual(self.instance.modified_at.date, today)74 self.assertEqual(content["value"], "-1")75 self.assertEqual(content["context"], "nested value")76 self.assertEqual(content["nested"], "nested value 0")77 self.assertEqual(content["extra"], "extra")78 instance = Document.objects.get(id=1)79 self.assertEqual(instance.properties["value"], "-1")80 self.assertEqual(instance.properties["context"], "nested value")81 self.assertEqual(instance.properties["nested"], "nested value 0")82 self.assertEqual(instance.properties["extra"], "extra")83 def test_update_using_doc(self):84 created_at = self.instance.created_at85 today = date.today()86 doc = Document.objects.create(properties={"value": "-1", "extra": "extra"})87 content = self.instance.update(doc)88 self.assertEqual(self.instance.created_at, created_at)89 self.assertNotEqual(self.instance.modified_at.date, today)90 self.assertEqual(content["value"], "-1")91 self.assertEqual(content["context"], "nested value")92 self.assertEqual(content["nested"], "nested value 0")93 self.assertEqual(content["extra"], "extra")94 instance = Document.objects.get(id=1)95 self.assertEqual(instance.properties["value"], "-1")96 self.assertEqual(instance.properties["context"], "nested value")97 self.assertEqual(instance.properties["nested"], "nested value 0")98 self.assertEqual(instance.properties["extra"], "extra")99 def test_update_no_commit(self):100 created_at = self.instance.created_at101 today = date.today()102 doc = Document.objects.create(properties={"value": "-1", "extra": "extra"})103 content = self.instance.update(doc, commit=False)104 self.assertEqual(self.instance.created_at, created_at)105 self.assertNotEqual(self.instance.modified_at.date, today)106 self.assertEqual(content["value"], "-1")107 self.assertEqual(content["context"], "nested value")108 self.assertEqual(content["nested"], "nested value 0")109 self.assertEqual(content["extra"], "extra")110 instance = Document.objects.get(id=1)111 self.assertEqual(instance.properties["value"], "0")112 self.assertEqual(instance.properties["context"], "nested value")113 self.assertEqual(instance.properties["nested"], "nested value 0")114 self.assertNotIn("extra", instance.properties)115 @patch("jsonschema.validate")116 def test_validate(self, jsonschema_validate):117 Document.validate(self.instance, self.schema)118 jsonschema_validate.assert_called_with(self.instance.properties, self.schema)119 jsonschema_validate.reset_mock()120 Document.validate(self.instance.properties, self.schema)121 jsonschema_validate.assert_called_with(self.instance.properties, self.schema)122 jsonschema_validate.reset_mock()123 Document.validate(self.instance.content, self.schema)124 jsonschema_validate.assert_called_with(self.instance.properties, self.schema)125 jsonschema_validate.reset_mock()126 try:127 Document.validate([self.instance], self.schema)128 except ValidationError:129 jsonschema_validate.assert_not_called()130 def test_validate_error(self):131 wrong_content = self.instance.content132 wrong_content["wrong"] = True133 try:134 Document.validate(wrong_content, self.schema)135 self.fail("Document.validate did not raise upon wrong content")136 except ValidationError:137 pass138 Document.validate(wrong_content, {"bullshit": "schema"})139 @patch('datatypes.models.Collection.influence')140 def test_clean_without_collective(self, influence_method):141 self.instance.collection = None142 self.instance.clean()143 influence_method.assert_not_called()144 @patch('datatypes.models.Collection.influence')145 def test_clean_with_collective(self, influence_method):146 self.instance.clean()147 influence_method.assert_called_once_with(self.instance)148 def test_getitem(self):149 value = self.instance["value"]150 self.assertEqual(value, self.instance.properties["value"])151 def test_setitem(self):152 self.instance["value"] = "new value"153 self.assertEqual(self.instance.properties["value"], "new value")154 def test_items(self):155 items = sorted(list(self.instance.items()))156 self.assertEqual(items, self.expected_items)157 def test_keys(self):158 expected_keys, expected_values = zip(*self.expected_items)159 keys = tuple(sorted(self.instance.keys()))160 self.assertEqual(keys, expected_keys)161 def test_values(self):162 expected_keys, expected_values = zip(*self.expected_items)163 expected_values = tuple(sorted(expected_values))164 values = tuple(sorted(self.instance.values()))...
app.py
Source:app.py
...78@is_valid_token79def product():80 json_data = request.get_json()81 try:82 jsonschema_validate(json_data, json_schema)83 if json_data["merchant_id"] != RICHARD_ID:84 raise abort(400, description="")85 except jsonschema_exceptions.ValidationError as e:86 raise abort(400, description=str(e))87 return json_data, 20088@app.route('/api/merchants', methods=["GET"])89@is_valid_token90def merchants():91 return merchants_data, 20092@app.route('/api/merchants/<merchant_id>', methods=["PUT", "DELETE"])93@is_valid_token94def update_merchant(merchant_id):95 if request.method == 'PUT':96 json_data = request.get_json()97 try:98 jsonschema_validate(json_data, merchant_schema)99 except jsonschema_exceptions.ValidationError as e:100 raise abort(400, description=str(e))101 if merchant_id == json_data["id"] == RICHARD_ID:102 return json_data, 200103 else:104 if merchant_id == BEAUTY_ID:105 return "", 200106 raise abort(400, description="")107@app.route("/ping")108@limiter.exempt109def ping():110 return "PONG", 200111@app.route("/")112@limiter.exempt...
jsonschema_validate.py
Source:jsonschema_validate.py
...32SCHEMA = os.path.join(TOP, "etc", "json", "behave.json-schema")33# -----------------------------------------------------------------------------34# FUNCTIONS:35# -----------------------------------------------------------------------------36def jsonschema_validate(filename, schema, encoding=None):37 f = open(filename, "r")38 contents = f.read()39 f.close()40 data = json.loads(contents, encoding=encoding)41 return validate(data, schema)42def main(args=None):43 """44 Validate JSON files against their JSON schema.45 NOTE: Behave's JSON-schema is used per default.46 SEE ALSO:47 * http://json-schema.org/48 * http://tools.ietf.org/html/draft-zyp-json-schema-0449 """50 if args is None:51 args = sys.argv[1:]52 default_schema = None53 if os.path.exists(SCHEMA):54 default_schema = SCHEMA55 parser = argparse.ArgumentParser(56 description=textwrap.dedent(main.__doc__),57 formatter_class=argparse.RawDescriptionHelpFormatter58 )59 parser.add_argument("-v", "--version",60 action="version", version=__version__)61 parser.add_argument("-s", "--schema",62 help="JSON schema to use.")63 parser.add_argument("-e", "--encoding",64 help="Encoding for JSON/JSON schema.")65 parser.add_argument("files", nargs="+", metavar="JSON_FILE",66 help="JSON file to check.")67 parser.set_defaults(68 schema=default_schema,69 encoding="UTF-8"70 )71 options = parser.parse_args(args)72 if not options.schema:73 parser.error("REQUIRE: JSON schema")74 elif not os.path.isfile(options.schema):75 parser.error("SCHEMA not found: %s" % options.schema)76 try:77 f = open(options.schema, "r")78 contents = f.read()79 f.close()80 schema = json.loads(contents, encoding=options.encoding)81 except Exception as e:82 msg = "ERROR: %s: %s (while loading schema)" % (e.__class__.__name__, e)83 sys.exit(msg)84 error_count = 085 for filename in options.files:86 validated = True87 more_info = None88 try:89 print("validate:", filename, "...", end=' ')90 jsonschema_validate(filename, schema, encoding=options.encoding)91 except Exception as e:92 more_info = "%s: %s" % (e.__class__.__name__, e)93 validated = False94 error_count += 195 if validated:96 print("OK")97 else:98 print("FAILED\n\n%s" % more_info)99 return error_count100# -----------------------------------------------------------------------------101# AUTO-MAIN102# -----------------------------------------------------------------------------103if __name__ == "__main__":104 sys.exit(main())
validator.py
Source:validator.py
...29 "status": Status.SUCCESS,30 "message": ""31 }32 try:33 jsonschema_validate(34 instance=instance_obj,35 schema=schema_obj,36 resolver=resolver37 )38 except ValidationError as e:39 result["status"] = Status.FAILURE,40 result["message"] = str(e)41 return result42 def validate(self):43 result = {44 "status": Status.SUCCESS,45 "message": ""46 }47 try:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!