def test_load_datetime_with_tz(self): tzinfo = datetime.timezone(datetime.timedelta(hours=-2)) dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=tzinfo) loaded = jsons.load('2018-07-08T21:34:00-02:00') self.assertEqual(loaded, dat)
def test_load_object_with_attr_getters(self): class A: def __init__(self, x, y): self.x = x self.y = y class B: def __init__(self, x): self.x = x a = A(1, 2) loaded_a = jsons.load({'x': 1}, A, attr_getters={'y': lambda: 2}) self.assertEqual(a.x, loaded_a.x) self.assertEqual(a.y, loaded_a.y) b = B(1) loaded_b = jsons.load({'x': 1}, B, attr_getters={'y': lambda: 2}) self.assertEqual(b.x, loaded_b.x) self.assertEqual(2, loaded_b.y)
def test_load_list(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) list_ = [1, 2, 3, [4, 5, [dat]]] expectation = [1, 2, 3, [4, 5, ['2018-07-08T21:34:00Z']]] self.assertEqual(list_, jsons.load(expectation))
def test_load_object_with_default_value(self): class A: def __init__(self, x, y = 2): self.x = x self.y = y a = A(1) loaded_a = jsons.load({'x': 1}, A) self.assertEqual(a.x, loaded_a.x) self.assertEqual(a.y, loaded_a.y)
def test_postponed_annoation_dataclass(self): from postponed_dataclass import Wrap obj = Wrap() exp = {'a': {'a': 42}} dump = jsons.dump(obj) self.assertDictEqual(exp, dump) undump = jsons.load(dump, cls=Wrap) self.assertEqual(undump, obj)
def test_load_default_dict_without_args(self): d = { 'a': [1, 2, 3], } dd = defaultdict(None, d) loaded = jsons.load(d, DefaultDict) self.assertEqual(dd.default_factory, loaded.default_factory)
def test_dump_load_endless_recursion(self): class Narcissus: @property def mirror(self): return self n = Narcissus() dumped_n = jsons.dump(n) loaded_n = jsons.load(dumped_n, Narcissus) self.assertTrue(isinstance(loaded_n.mirror.mirror.mirror, Narcissus))
def test_load_datetime_with_ms(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, second=0, microsecond=123456, tzinfo=datetime.timezone.utc) self.assertEqual(dat, jsons.load('2018-07-08T21:34:00.123456Z'))
def test_load_tuple(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) tup = (1, ([dat], )) expectation = (1, (['2018-07-08T21:34:00Z'], )) cls = Tuple[int, Tuple[List[datetime.datetime]]] self.assertEqual(tup, jsons.load(expectation, cls))
def test_load_tuple_with_n_length(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) expectation = (dat, dat) loaded = jsons.load(['2018-07-08T21:34:00Z', '2018-07-08T21:34:00Z'], cls=Tuple[datetime.datetime, ...]) self.assertEqual(expectation, loaded)
def post(self): """POST a collection of units or a single unit item""" #try loading the collection try: Units = jsons.load(request.get_json(), cls=UnitsDto, strict=True) iscollection = True except: iscollection = False #if not a collection load a single item, returns 404 as error if not iscollection: try: Unit = jsons.load(request.get_json(), cls=UnitDto, strict=True) except: raise w_exc.BadRequest() if iscollection: helper.AddUnits(Units) return {"message": "created"}, 201 else: helper.AddUnit(Unit) return {"message": "created"}, 201
def test_uuid_serialization(self): from version_with_dataclasses import User user = User(uuid.uuid4(), 'name') dumped = jsons.dump(user) self.assertEqual(dumped['user_uuid'], str(user.user_uuid)) loaded = jsons.load(dumped, User) self.assertEqual(user.user_uuid, loaded.user_uuid) self.assertEqual('name', loaded.name)
def test_dump_windows_load_windows(self): dump_result = jsons.dump(PureWindowsPath('abc', 'def', 'ghi')) self.assertEqual( 'abc/def/ghi', dump_result ) load_result = jsons.load(dump_result, PureWindowsPath) self.assertEqual( PureWindowsPath('abc', 'def', 'ghi'), load_result )
def test_load_partially_deserialized_dict(self): class C: def __init__(self, d: datetime.datetime): self.d = d dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) dumped = {'d': dat} loaded = jsons.load(dumped, C) self.assertEqual(loaded.d, dat)
def showUnattemptedContests(request, team_encrypted_id): if request.user.is_authenticated: team_id = signing.loads(team_encrypted_id)['id'] team = User_Team.objects.get(id = team_id) id = request.user.handle + str(team) + '?contestList' contestList = cache.get(id) if not contestList or request.GET.get('refresh'): data = getUnattemptedContests([team.creator_user.handle, team.handle2, team.handle3]) if data[0]: contestList = data[1] cache.set(id, jsons.dump(contestList), settings.UPDATE_TIME) print('Added in cache') else: return HttpResponse( 'There might be some error or your team may have participated in all contests.' + 'Try with a different team.' ) else: contestList = jsons.load(contestList) print('Retrieved from cache') filter_types = request.GET.get('types', '') filter_types = list(set(filter_types.split('|'))) filter_types = [i.upper() for i in filter_types] if '' in filter_types: filter_types.remove('') if filter_types: to_delete = [] for c_id, contest in contestList.items(): if contest['type'] not in filter_types: to_delete.append(c_id) for c_id in to_delete: del contestList[c_id] paginator = Paginator( list(contestList.values()), per_page = 30) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) return render( request, template_name = 'cfFrenemies/showunattemptedcontests.html', context = { 'contestList': page.object_list, 'paginator': paginator, 'team_encrypted': team_encrypted_id } ) else: redirect('login')
def test_load_defaultdict(self): d = { 'a': [1, 2, 3], } dd = defaultdict(list, d) loaded = jsons.load(d, DefaultDict[str, list]) self.assertDictEqual(dd, loaded) self.assertIsInstance(loaded, defaultdict) self.assertEqual(list, loaded.default_factory)
def read_config(path='./config.json'): config = None with open(path) as file: try: dict_config = json.load(file, encoding='utf8') config = jsons.load(dict_config, ConstraintsConfig) except FileNotFoundError: print(path + " not found. ") except ValueError: print("parse error") return config
def load(path: str) -> Recipe: """ Load one Recipe based on a .json file. :param path: A relative path (from repo root) to a recipe file. Example: 'recipes/apple/privacy.json'. """ with open(path, 'r') as fp: item = json.load(fp) item['path'] = path item['path_repo'] = __repo_path() item['asession'] = asession return jsons.load(item, Recipe)
def _parse_tree(data: Any, tree_structure: Any) -> Any: level_type = tree_structure.__class__ if level_type not in ITERABLES: return jsons.load(data, tree_structure) if level_type == list: return _parse_list(data, tree_structure) if level_type == dict: return _parse_dict(data, tree_structure)
def test_dump_posix_load_posix(self): dump_result = jsons.dump(PurePosixPath('abc', 'def', 'ghi')) self.assertEqual( 'abc/def/ghi', dump_result ) load_result = jsons.load(dump_result, PurePosixPath) self.assertEqual( PurePosixPath('abc', 'def', 'ghi'), load_result )
def former_scans(): site = request.args.get('q', default='') if site: docs = collection.find({'site': site}).sort("timestamp", pymongo.DESCENDING).limit(20) else: docs = collection.find({}).sort("timestamp", pymongo.DESCENDING).limit(20) scans = [] for doc in docs: res = jsons.load(doc, SuccessResult) score = Scorer(res).total_score() scans.append((doc, score)) return render_template('formerScans.html', site=site, former_scans=scans)
def test_load_list_typing(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) expectation = [1, 2, 3, [4, 5, [dat]]] loaded = jsons.load([1, 2, 3, [4, 5, ['2018-07-08T21:34:00Z']]], List) self.assertEqual(expectation, loaded)
def test_load_list_with_generic(self): class C: def __init__(self, x: str, y: int): self.x = x self.y = y expectation = [C('a', 1), C('b', 2)] loaded = jsons.load([{'x': 'a', 'y': 1}, {'x': 'b', 'y': 2}], List[C]) self.assertEqual(expectation[0].x, loaded[0].x) self.assertEqual(expectation[0].y, loaded[0].y) self.assertEqual(expectation[1].x, loaded[1].x) self.assertEqual(expectation[1].y, loaded[1].y)
def test_load_multipart_drived_pure_windows_path(self): # We should be able to load Posix-style paths on Windows. self.assertEqual( PureWindowsPath('Z:\\', 'abc', 'def', 'ghi'), jsons.load('Z:/abc/def/ghi', PureWindowsPath) ) self.assertEqual( PureWindowsPath('Z:/abc/def/ghi'), jsons.load('Z:/abc/def/ghi', PureWindowsPath) ) self.assertEqual( PureWindowsPath('Z:\\abc\\def\\ghi'), jsons.load('Z:/abc/def/ghi', PureWindowsPath) ) # We should be able to load Windows-style paths on Windows. self.assertEqual( PureWindowsPath('Z:\\', 'abc', 'def', 'ghi'), jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) ) self.assertEqual( PureWindowsPath('Z:/abc/def/ghi'), jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) ) self.assertEqual( PureWindowsPath('Z:\\abc\\def\\ghi'), jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) )
def test_load_multipart_drived_pure_posix_path(self): # We should be able to load Posix-style paths on Windows. self.assertEqual( PurePosixPath('Z:', 'abc', 'def', 'ghi'), jsons.load('Z:/abc/def/ghi', PurePosixPath) ) self.assertEqual( PurePosixPath('Z:/abc/def/ghi'), jsons.load('Z:/abc/def/ghi', PurePosixPath) ) self.assertNotEqual( PurePosixPath('Z:\\abc\\def\\ghi'), jsons.load('Z:/abc/def/ghi', PurePosixPath) ) # Backslashes on Posix systems should be interpreted as escapes. self.assertNotEqual( PurePosixPath('Z:', 'abc', 'def', 'ghi'), jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) ) self.assertNotEqual( PurePosixPath('Z:/abc/def/ghi'), jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) ) self.assertEqual( PurePosixPath('Z:\\abc\\def\\ghi'), jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) )
def test_name_in_field_list_when_body_is_set_to_all(sbdb_close_approach_data_client): """ Given: I have close approach data client. And: I add body param with value "All". When: I make the call. Then: I should get back 200 Ok and body in fields list. """ sbdb_close_approach_data_client.add_query_param(body="All") status, response = sbdb_close_approach_data_client.get() assert status == 200 response_class_obj = jsons.load(response, cls=SBDBCloseApproachResponse) assert "body" in response_class_obj.fields sbdb_close_approach_data_client.add_query_param(body="Earth") status, response = sbdb_close_approach_data_client.get() assert status == 200 response_class_obj = jsons.load(response, cls=SBDBCloseApproachResponse) assert "body" not in response_class_obj.fields
def test_load_object_properties(self): class WithoutSetter: @property def x(self): return 123 class WithSetter: def __init__(self): self.__x = 123 @property def x(self): return self.__x @x.setter def x(self, x): self.__x = x loaded1 = jsons.load({'x': 123}, WithoutSetter) self.assertEqual(loaded1.x, 123) loaded2 = jsons.load({'x': 456}, WithSetter) self.assertEqual(loaded2.x, 456)
def test_load_recursive_structure(self): source = { 'value': 10, 'next': { 'value': 20, 'next': { 'value': 30, 'next': None } } } loaded = jsons.load(source, Node) self.assertEqual(30, loaded.next.next.value)
def test_dump_nested_object_roundtrip(self): class A: def __init__(self, inner): self.inner = inner class B: pass obj = A(A(B())) obj_roundtrip = jsons.load(jsons.dump(obj, verbose=True)) self.assertTrue(isinstance(obj_roundtrip, A)) self.assertTrue(isinstance(obj_roundtrip.inner, A)) self.assertTrue(isinstance(obj_roundtrip.inner.inner, B))
def test_dump_load_newtype(self): Uid = NewType('uid', str) class User: def __init__(self, uid: Uid, name: str): self.uid = uid self.name = name dumped = jsons.dump(User('uid', 'name')) loaded = jsons.load(dumped, User) self.assertEqual('uid', loaded.uid) self.assertEqual('name', loaded.name)
# # print c # print c['a'] # print str(c['a']) #Note: #1.Also, if you write jsons script from python, #you should use dump instead of load. pleaser refer to "help(jsons)". #jsons file: #The file content of temp.jsons is: #{ # "name":"00_sample_case1", # "description":"an example." #} f = file("temp.jsons"); s = jsons.load(f) print s f.close with open('d:/practice.json') as file: sc = file.readline() s = json.loads(sc) #print s.keys() #for key in s.keys(): #print key #print s[key] for key in s["workExperienceList"][0].iterkeys(): print key + ':' print s["workExperienceList"][0][key]