def test_get_name_from_symbol(self): # valid company name with patch("requests.get") as my_mock: m2 = MagicMock() m2.json.return_value = {'result': {'rows': [{'values': [{'field': 'companyname', 'value': 'Microsoft'}]}]}} my_mock.return_value = m2 self.assertEqual(get_name_from_symbol("MSFT"), "Microsoft") ## invalid symbol with patch("requests.get") as my_mock: m2 = MagicMock() m2.json.return_value = {'result': {'rows': [{'values': [{'field': 'companyname', 'value': 'Microsoft'}]}]}} my_mock.return_value = m2 self.assertEqual(get_name_from_symbol("ZZZZ123"), None) ## throw exception with patch("requests.get") as my_mock: my_mock.r.json.side_effect = KeyError self.assertEqual(get_name_from_symbol("MSFT"), None)
def from_json(json_indicators): """ Args: json_indicators: name, symbol, **attributes If company does not exist, must provide a name and symbol to create it. Returns: An Indicator object """ symbol = json_indicators.get('symbol') if not symbol: return None indicators = Indicators() # Get company if it exists, otherwise create it if not Company.query.filter_by(symbol=symbol).first(): name = json_indicators.get('name') or get_name_from_symbol(symbol) if not name: return None company = Company(symbol=symbol, name=name) db.session.add(company) db.session.commit() else: company = Company.query.filter_by(symbol=symbol).first() # Go through each key and assign it, unless it's "name" or "symbol" for key in json_indicators.keys(): if key.find(".") == -1 and key != 'name' and key != 'symbol' and key != "company_id" and key != "id": setattr(indicators, key, json_indicators.get(key)) indicators.company = company return indicators