def test_should_not_return_company_if_user_is_not_your_manager(self): company = CompanyFactory(created_by=self.superuser) other_company = CompanyFactory(created_by=self.superuser) manager = ManagerFactory(company=company) self.set_client_token(user=manager) response = self.client.get(reverse('companies:company-detail', kwargs={'pk': other_company.pk})) self.response_403(response)
def test_model_creation_invalid_cnpj(self): """ Should fail to create an instance of Company in the database when the cnpj value is invalid """ self.assertEqual(Company.objects.count(), 0) # tests invalid cnpj value company = CompanyFactory.build() company.cnpj = "11.111.111/1111-11" expected_messages = { "cnpj": [f"Ensure the CNPJ is valid (it is {company.cnpj})."] } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0) # tests invalid cnpj length company = CompanyFactory.build() company.cnpj = company.cnpj + "1" expected_messages = { "cnpj": [ f"Ensure the CNPJ is valid (it is {company.cnpj}).", f"Ensure this value has at most {CNPJ_SIZE} characters " f"(it has {len(company.cnpj)}).", ], } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0)
def setUp(self): self.test_data = {} companies = [ CompanyFactory.build().__dict__, CompanyFactory.build().__dict__, ] for data in companies: clean_data = remove_attributes(data) self.test_data[clean_data["cnpj"]] = clean_data
def test_company_stock_valuation(self, time_series_mock): company = CompanyFactory() time_series_mock.return_value.get_quote_endpoint.return_value = ( { '01. symbol': 'AAPL', '02. open': '176.7300', '03. high': '181.2600', '04. low': '174.9300', '05. price': '180.9400', '06. volume': '42348987', '07. latest trading day': '2018-11-28', '08. previous close': '174.2400', '09. change': '6.7000', '10. change percent': '3.8453%' }, None ) response = company_stock_valuation(company) self.assertDictEqual(response, { 'open': '176.7300', 'high': '181.2600', 'low': '174.9300', 'close': '180.9400', 'price': '180.9400', 'volume': '42348987' }) time_series_mock.assert_called_once_with(key=settings.ALPHA_VANTAGE_API_KEY) time_series_mock.return_value.get_quote_endpoint.assert_called_once_with(company.symbol)
def test_interaction_with_filter_by_company(self): company_1 = CompanyFactory() company_2 = CompanyFactory() for _ in range(2): InteractionFactory(project=ProjectFactory(company=company_1)) InteractionFactory(project=ProjectFactory(company=company_2)) response = self.client.get(f"{reverse('interaction:list')}?company={company_1.pk}") self.assertEqual(response.status_code, 200) self.assertEqual(response.context['interaction_list'].count(), 2) response = self.client.get(f"{reverse('interaction:list')}?company={company_2.pk}") self.assertEqual(response.status_code, 200) self.assertEqual(response.context['interaction_list'].count(), 1)
def test_serializer(self): data = {} serializer = CompanyRequestSerializer(data=data) self.assertFalse(serializer.is_valid()) self.assertDictEqual( serializer.errors, { 'company': [ ErrorDetail(string='This field is required.', code='required') ] }) data = {'company': 'AB'} serializer = CompanyRequestSerializer(data=data) self.assertFalse(serializer.is_valid()) self.assertDictEqual( serializer.errors, { 'company': [ ErrorDetail( string='Invalid pk "AB" - object does not exist.', code='does_not_exist') ] }) CompanyFactory(symbol='AB') serializer = CompanyRequestSerializer(data=data) self.assertTrue(serializer.is_valid())
def test_company_list_is_not_empty(self): for _ in range(3): CompanyFactory() response = self.client.get(reverse('company:list')) self.assertEqual(response.status_code, 200) self.assertNotContains(response, "Список компаний пуст.") self.assertEqual(response.context['company_list'].count(), 3)
def test_model_creation_duplicate_cnpj(self): """ Should fail to create multiple instances of Company in the database with the same CNPJ """ self.assertEqual(Company.objects.count(), 0) company = CompanyFactory.create() self.assertEqual(Company.objects.count(), 1) company_two = CompanyFactory.build() company_two.cnpj = company.cnpj expected_messages = { "cnpj": ["Company with this Cnpj already exists."] } with self.assertRaises(ValidationError) as raised: company_two.save() self.assertEqual(raised.exception.message_dict, expected_messages)
def test_company_info(self, update_details_mock): company = CompanyFactory(has_extra_info=False) company_info(company) update_details_mock.assert_not_called() company = CompanyFactory(has_extra_info=True) company_info(company) update_details_mock.assert_not_called() company = CompanyFactory(has_extra_info=None) company_info(company) update_details_mock.assert_called_once_with(company)
def test_serializer(self): company = CompanyFactory() serializer = CompanySearchSerializer(instance=company) self.assertDictEqual(serializer.data, { 'symbol': company.symbol, 'name': company.name })
def test_view(self, company_info_mock): company = CompanyFactory() company_info_mock.return_value = company data = dict(company=company.symbol) response = self.client.get(self.url, data=data) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), CompanyInfoSerializer(company).data) company_info_mock.assert_called_once_with(company)
def test_create_company(self): company_from_factory = CompanyFactory() self.assertEqual(Company.objects.count(), 1) company_from_db = Company.objects.first() self.assertEqual(company_from_factory.name, company_from_db.name) self.assertEqual(company_from_factory.contact_person, company_from_db.contact_person) self.assertEqual(company_from_factory.description, company_from_db.description) self.assertEqual(company_from_factory.address, company_from_db.address)
def test_serializer(self): company = CompanyFactory() serializer = CompanyInfoSerializer(instance=company) self.assertDictEqual( serializer.data, { 'symbol': company.symbol, 'name': company.name, 'logo': company.logo, 'website': company.website })
def test_model_creation(self): """Should successfully create an instance of Company in the database""" self.assertEqual(Company.objects.count(), 0) company = CompanyFactory.create() self.assertEqual(Company.objects.count(), 1) retrieved_company = Company.objects.first() self.assertEqual(company.name, retrieved_company.name) self.assertEqual(company.cnpj, retrieved_company.cnpj) self.assertEqual(company.owner, retrieved_company.owner) self.assertEqual(company.ddd, retrieved_company.ddd) self.assertEqual(company.phone, retrieved_company.phone)
def test_company_report_serializer(self): company = CompanyFactory.build() serialized_data = CompanyReportSerializer(company).data for serializer_field, model_field in field_mappings.items(): self.assertIn(serializer_field, serialized_data) value = getattr(company, model_field) if serializer_field == "telefone": value = str(value) self.assertEqual(serialized_data[serializer_field], value)
def test_view(self, company_current_price_mock): company_current_price_mock.return_value = dict(is_open=True, price='12.532') company = CompanyFactory() data = dict(company=company.symbol) response = self.client.get(self.url, data=data) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), company_current_price_mock.return_value) company_current_price_mock.assert_called_once_with(company)
def test_model_creation_invalid_phone(self): """ Should fail to create an instance of Company in the database when the phone value is invalid """ self.assertEqual(Company.objects.count(), 0) # tests invalid phone value below expected length company = CompanyFactory.build() company.phone = 11111111 expected_messages = { "phone": [ f"Ensure the length of this value is between {PHONE_SIZE} " f"and {PHONE_SIZE} (it is {len(str(company.phone))})." ] } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0) # tests invalid phone value above expected length company = CompanyFactory.build() company.phone = 1111111111 expected_messages = { "phone": [ f"Ensure the length of this value is between {PHONE_SIZE} " f"and {PHONE_SIZE} (it is {len(str(company.phone))})." ] } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0)
def test_model_creation_invalid_ddd(self): """ Should fail to create an instance of Company in the database when the ddd value is invalid """ self.assertEqual(Company.objects.count(), 0) # tests invalid ddd value below lower limit company = CompanyFactory.build() company.ddd = 10 expected_messages = { "ddd": [ f"Ensure this value is greater than or equal to " f"{DDD_LOWER_LIMIT}." ] } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0) # tests invalid ddd value above upper limit company = CompanyFactory.build() company.ddd = 100 expected_messages = { "ddd": [ f"Ensure this value is less than or equal to " f"{DDD_UPPER_LIMIT}." ] } with self.assertRaises(ValidationError) as raised: company.save() self.assertEqual(raised.exception.message_dict, expected_messages) self.assertEqual(Company.objects.count(), 0)
def test_view(self, company_stock_valuation_mock): company_stock_valuation_mock.return_value = dict(open='107.8900', high='111.0800', low='107.8600', close='110.7966', price='110.7966', volume='27402176') company = CompanyFactory() data = dict(company=company.symbol) response = self.client.get(self.url, data=data) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), company_stock_valuation_mock.return_value) company_stock_valuation_mock.assert_called_once_with(company)
def test_view(self, company_search_mock): company = CompanyFactory() company_search_mock.return_value = [company] response = self.client.get(self.url) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), ['Missing query parameter']) data = dict(query='AA') response = self.client.get(self.url, data) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), [CompanySearchSerializer(company).data]) company_search_mock.assert_called_once_with(data['query'])
def test_company_factory(self): """ Should successfully get an instance of Company with populated attributes """ company = CompanyFactory() self.assertIsInstance(company, Company) self.assertIsInstance(company.name, str) self.assertTrue(len(company.name) > 1) self.assertIsInstance(company.cnpj, str) self.assertTrue(len(company.cnpj) > 1) self.assertIsInstance(company.owner, str) self.assertTrue(len(company.owner) > 1) self.assertIsInstance(company.ddd, int) self.assertGreaterEqual(company.ddd, DDD_LOWER_LIMIT) self.assertLessEqual(company.ddd, DDD_UPPER_LIMIT) self.assertIsInstance(company.phone, int) self.assertEqual(len(str(company.phone)), PHONE_SIZE)
def test_is_market_open(self, timezone_offset_mock): timezone_offset_mock.return_value = dict(hours=-5, minutes=0) company = CompanyFactory(market_open=datetime.time(9, 30), market_close=datetime.time(16)) with freeze_time("2018-12-2 18:00:00"): self.assertFalse(is_market_open(company)) with freeze_time("2018-12-3 14:30:00"): self.assertTrue(is_market_open(company)) with freeze_time("2018-12-3 18:00:00"): self.assertTrue(is_market_open(company)) with freeze_time("2018-12-3 21:00:00"): self.assertTrue(is_market_open(company)) with freeze_time("2018-12-3 21:01:00"): self.assertFalse(is_market_open(company))
def test_company_current_price(self, get_daily_mock, is_market_open_mock): is_market_open_mock.return_value = False time_series = { "2018-11-30": { "1. open": "110.7000", "2. high": "110.9700", "3. low": "109.3600", "4. close": "110.8900", "5. volume": "33641467" } } meta_data = { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "MSFT", "3. Last Refreshed": "2018-11-30", "4. Output Size": "Compact", "5. Time Zone": "US/Eastern" } get_daily_mock.return_value = time_series, meta_data company = CompanyFactory() self.assertDictEqual(company_current_price(company), dict(is_open=False, price=None)) is_market_open_mock.return_value = True self.assertDictEqual(company_current_price(company), dict(is_open=True, price=None)) time_series["2018-12-02"] = { "1. open": "107.8900", "2. high": "111.3300", "3. low": "107.8600", "4. close": "111.1200", "5. volume": "46788461" } self.assertDictEqual(company_current_price(company), dict(is_open=True, price='111.1200'))
def setUpTestData(cls): UserModel.objects.create_user(username='******', password='******') CompanyFactory()
def test_company_full_phone(self): """Should successfully get the full phone number of a Company""" company = CompanyFactory.build() self.assertEqual(company.full_phone, int(f"{company.ddd}{company.phone}"))
def test_company_string_representation(self): """ Should successfully get a correct string representation of a Company """ company = CompanyFactory.build() self.assertEqual(str(company), f"{company.name} ({company.cnpj})")
def test_unique_name_company(self): company = CompanyFactory() with self.assertRaises(IntegrityError): CompanyFactory(name=company.name)
def test_should_not_return_company_if_user_has_not_a_company(self): company = CompanyFactory(created_by=self.superuser) user = self.make_user({'username': fake.user_name(), 'password': fake.password()}) self.set_client_token(user=user) response = self.client.get(reverse('companies:company-detail', kwargs={'pk': company.pk})) self.response_403(response)
def test_should_return_list_of_company_headquarters_if_user_is_your_manager(self): company = CompanyFactory(created_by=self.superuser) manager = ManagerFactory(company=company) self.set_client_token(user=manager) response = self.client.get(reverse('companies:company-headquarters', kwargs={'pk': company.pk})) self.response_200(response)
def test_should_return_company_headquarters_list_if_user_is_manager(self): company = CompanyFactory(created_by=self.superuser) manager_user = ManagerFactory(company=company) self.set_client_token(user=manager_user) response = self.client.get(reverse('companies:headquarter-list')) self.response_200(response)