def __get_smart_from_json_conversion(cls, key, value, json_name="json", array=False): ref_type, possible_refs = cls.__get_possible_refs(value) if array: from_json = "newObject.{0}.append(".format(utils.to_camel_case(key)) else: from_json = "newObject.{0} = ".format(utils.to_camel_case(key)) if ref_type == u"full": from_json += "{0}.fromJson({1}[\"{2}\"]!)".format(utils.to_camel_case(possible_refs[0], capital=True), json_name, key) if array: from_json += ") " from_json += cls.__get_other_possible_refs(possible_refs) elif ref_type == u"id": from_json += "{0}[\"{1}\"].intValue".format(json_name, key) if array: from_json += ")\n" elif ref_type == u"uri": from_json += "{0}[\"{1}\"].stringValue".format(json_name, key) if array: from_json += ")\n" else: raise ConfigurationFileException("Wrong reference type specified for key {0}: {1}. Use: [full, id, uri]" .format(key, ref_type)) return from_json
def __get_smart_to_json_conversion_for_array(cls, key, value): ref_type, possible_refs = cls.__get_possible_refs(value) if ref_type == u"full": to_json = "var {0}Array = [JSON]()\n".format(utils.to_camel_case(key)) to_json += "\t\tfor obj in self.{0}".format(utils.to_camel_case(key)) + " {\n" to_json += "\t\t\t {0}Array.append(obj.toJson())\n".format(utils.to_camel_case(key)) to_json += "\t\t}\n" to_json += "\t\tjson[\"{0}\"] = {1}Array".format(key, utils.to_camel_case(key)) return to_json else: return "json[\"{0}\"].arrayValue = self.{1}".format(key, utils.to_camel_case(key))
def test_server_update_user_portfolio_endpoint(self): server = BackendServer(host=self.host, port=self.port) server.start() # make a request on the end point as get resp = requests.get( f"http://{self.host}:{self.port}/api/update_user_portfolio") self.assertEqual(resp.status_code, 405) # make valid request to the endpoint json_data = dict() json_data["currency"] = Currencies.GBP.name json_data["email"] = "*****@*****.**" # generate asset and liabilities data cash, use, invested, current, long = utils.get_test_assets_and_liabilities( ) # cash Assets vals = {utils.to_camel_case(k): v for k, v in cash.__dict__.items()} vals["other"] = cash.other.__dict__ json_data["cashAssets"] = vals # use Assets vals = {utils.to_camel_case(k): v for k, v in use.__dict__.items()} vals["other"] = use.other.__dict__ json_data["useAssets"] = vals # invested Assets vals = { utils.to_camel_case(k): v for k, v in invested.__dict__.items() } vals["otherTax"] = invested.other_tax.__dict__ vals["otherBusiness"] = invested.other_business.__dict__ json_data["investedAssets"] = vals vals = {utils.to_camel_case(k): v for k, v in current.__dict__.items()} vals["other"] = current.other.__dict__ json_data["currentLiabilities"] = vals vals = {utils.to_camel_case(k): v for k, v in long.__dict__.items()} vals["other"] = long.other.__dict__ json_data["longTermLiabilities"] = vals resp = requests.post( f"http://{self.host}:{self.port}/api/update_user_portfolio", json=json_data) self.assertEqual(resp.status_code, 200) server.stop()
def __get_from_json_conversion(cls, key, value): if value.startswith(u":"): from_json = cls.__get_smart_from_json_conversion(key, value[1:]) elif value.startswith(u"["): from_json = "newObject.{0} = []\n".format(utils.to_camel_case(key)) from_json += "\t\tfor subJson in json[\"{0}\"] ".format(key) + "{\n" from_json += "\t\t\t" + cls.__get_smart_from_json_conversion(key, value[2:-1], "subJson", True) from_json += "\n\t\t}" else: from_json = "newObject.{0} = json[\"{1}\"].{2}".format(utils.to_camel_case(key), key, SWIFTY_JSON_TYPES_MAP[value]) if value == u"date": from_json = "//" + from_json + "\t// please add appropriate conversion!" return from_json
def __get_smart_to_json_conversion(cls, key, value): ref_type, possible_refs = cls.__get_possible_refs(value) to_json = "json[\"{0}\"]".format(key) if ref_type == u"full": to_json += " = self.{0}.toJson()".format(utils.to_camel_case(key, capital=False)) del possible_refs[0] to_json += cls.__get_other_possible_refs(possible_refs) elif ref_type == u"id": to_json += ".intValue = self.{0}".format(utils.to_camel_case(key)) elif ref_type == u"uri": to_json += ".stringValue = self.{0}".format(utils.to_camel_case(key)) else: raise ConfigurationFileException("Wrong reference type specified for key {0}: {1}. Use: [full, id, uri]" .format(key, ref_type)) return to_json
def build(current_dict: defaultdict, headings: [], element: JsonSchemaElement): heading = to_camel_case(headings[0]) if len(headings) > 1: next_dict = defaultdict() current_dict[heading] = next_dict sub_headings = headings[1:] build(next_dict, sub_headings, element) else: current_dict[heading] = element.default_value
def update_element_output_name_with_object_delimiter( delimited_heading: [], element: JsonSchemaElement): output_name: str = "" for i, heading in enumerate(delimited_heading): output_name += to_camel_case(heading) if i < len(delimited_heading) - 1: output_name += const.OBJECT_DELIMITER element.output_name = output_name
def __getattr__(self, item): """ Cog specific getattr to attempt resolving other cog names. Basically a dynamic alias system. :param item: Name of the attribute to get :return: Cog instance if one exists on the bot """ cog = self.bot.cogs.get(utils.to_camel_case(item)) if cog is None: raise AttributeError return cog
def test_case_converters(): test_str = "lower_snake_case" expected = "LowerSnakeCase" result = utils.to_camel_case(test_str) assert result == expected, "Snake case not converted to upper camel case" expected = "lowerSnakeCase" result = utils.to_camel_case(test_str, False) assert result == expected, "Snake case not converted to lower camel case" test_str = "UpperCamelCase" expected = "upper_camel_case" result = utils.to_snake_case(test_str) assert result == expected, "Camel case not converted to lower snake case" expected = "UPPER_CAMEL_CASE" result = utils.to_snake_case(test_str, True) assert result == expected, "Camel case not converted to upper snake case"
def _parse_heading(heading: str): is_array = const.ARRAY_INDICATOR_KEY in heading if is_array: heading = heading.replace(const.ARRAY_INDICATOR_KEY, "") if "{" and "=" and "}" in heading: index_left = heading.rindex("{") index_right = heading.rindex("}") if index_left < index_right: equals_indexes = get_indexes_of_equal_signs(heading) if is_equality_assignment_between_braces(equals_indexes, index_left, index_right): extracted_heading = to_camel_case(heading[0:index_left]) properties_substring = heading[index_left + 1:index_right].lower() return extracted_heading, properties_substring, is_array return to_camel_case(heading), None, is_array
def __get_other_possible_refs(cls, refs): del refs[0] result = "" if len(refs) > 0: result = "\t// or " for ref in refs: result += "{0} ".format(utils.to_camel_case(ref, capital=True)) result += "- please choose appropriate conversion" return result
def __get_member_declaration(self, key, value): # exception for fields describing objects themselves, not other references to other objects member_name = utils.to_camel_case(key) if value.startswith(u"["): member_type = self.__get_member_type(value[1:-1], True) else: member_type = self.__get_member_type(value) member_declaration = "var {0}: {1}".format(member_name, member_type) return member_declaration
def __build(self): for p in self.__cfg: spec = {} if type(p) == str: # assuming this doesn't require a spec classname = to_camel_case(p) elif 'kind' in p: classname = to_camel_case(p['kind']) else: logging.error("Don't know how to parse : " + str(p)) raise ValueError if 'spec' in p: spec = p['spec'] try: self.__nodes.append(globals()[classname](spec)) except KeyError as e: logging.fatal("Couldn't not create object of class " + classname + str(e)) # wire them up in sequence only TODO: support complex plumbing for o in range(0, len(self.__nodes) - 1): self.__nodes[o].hook(self.__nodes[o + 1])
def __get_member_user_type(cls, value, array=False): ref_type, possible_refs = cls.__get_possible_refs(value) if ref_type == u"full": output = utils.to_camel_case(possible_refs[0], capital=True) + "?" if array: output = "[{0}]".format(output) del possible_refs[0] if len(possible_refs) > 0: output += "\t//" for ref in possible_refs: output += " or " + utils.to_camel_case(ref, capital=True) + "?" output += " - please choose appropriate type" elif ref_type == u"id": output = "Int?" elif ref_type == u"uri": output = "String?" else: output = "" return output
def as_json_dict(self): data = {} for key, value in self.__dict__.items(): camel_key = utils.to_camel_case(key) if isinstance(value, (list, tuple, set)): data[camel_key] = list() for item in value: if hasattr(item, 'as_json_dict'): data[camel_key].append(item.as_json_dict()) else: data[camel_key].append(item) elif hasattr(value, 'as_json_dict'): data[camel_key] = value.as_json_dict() elif value is not None: data[camel_key] = value return data
def get(self): with model.session_scope() as session: user_session = self.get_user_session(session) user_session.policy.verify('conf_view') settings = {} for name, schema in config.SCHEMA.items(): if config.is_private(name, schema): continue s = schema.copy() s['name'] = to_camel_case(name) if 'default_file_path' in s: del s['default_file_path'] s['value'] = config.get_setting(session, name) settings[name] = s self.set_header("Content-Type", "application/json") self.write(json_encode(ToSon()(settings))) self.finish()
def generate(self): output = DISCLAIMER + "\n\n" for parsed_value in self.parsed_values: class_name = utils.to_camel_case(parsed_value[self.file_name_key][0:-5], capital=True) origin = "" if ORIGIN_KEY in parsed_value: origin = "which was generated from json file: {0}".format(parsed_value[ORIGIN_KEY]) parsed_value.pop(ORIGIN_KEY, None) output += "// generated from config file: {0} {1}\n".format(parsed_value[self.file_name_key], origin) output += "class {0}".format(class_name) + " {\n" parsed_value.pop(self.file_name_key, None) to_json_body = "" from_json_body = "" for key in parsed_value: value = parsed_value[key] #key = self.__remove_id_and_uri(key) member_declaration = self.__get_member_declaration(key, value) to_json = self.__get_to_json_conversion(key, value) from_json = self.__get_from_json_conversion(key, value) to_json_body += "\t\t{0}\n".format(to_json) from_json_body += "\t\t{0}\n".format(from_json) output += "\t{0}\n".format(member_declaration) output += "\n" to_json = self.__add_to_json_method(to_json_body) from_json = self.__add_from_json_method(from_json_body, class_name) output += "{0}\n\n{1}\n".format(from_json, to_json) output += "}\n\n" if self.persist_output: self.output = output else: print output
def test_to_camel_case(): text = "A simple text With SoMe WeIrD cHaracteR" result = tested_utils.to_camel_case(text) assert result == "ASimpleTextWithSomeWeirdCharacter"
def __get_to_json_conversion(cls, key, value): if value.startswith(u":"): to_json = cls.__get_smart_to_json_conversion(key, value[1:]) elif value.startswith(u"["): to_json = cls.__get_smart_to_json_conversion_for_array(key, value[2:-1]) else: to_json = "json[\"{0}\"].{1} = self.{2}".format(key, SWIFTY_JSON_TYPES_MAP[value], utils.to_camel_case(key)) if value == u"date": to_json = "//" + to_json + "\t// please add appropriate conversion!" return to_json