def test_save_proper_request(self): serializer = CarPostSerializer(data=self.serializer_data) serializer.is_valid() with patch("cars.serializers.requests.get") as mock_get: mock_get.return_value.ok = True mock_get.return_value.json.return_value = self.external_API_Response self.assertEqual(serializer.save(), self.car)
def test_model_not_in_db_car_post(self): """ Manufacturer already exists in db. Model doesn't exist in db.""" request = factory.post(self.url, { "make": "Ford", "model": "Mustang" }, format="json") Manufacturer.objects.create(make="Ford") with self.assertRaises(Car.DoesNotExist): Car.objects.get(model="Mustang") with patch("cars.serializers.requests.get") as mock_get: mock_get.return_value.ok = True mock_get.return_value.json.return_value = self.external_API_Response response = self.view(request) response.render() car = Car.objects.get(model="Mustang") serializer = CarPostSerializer(car) manufacturer_count = Manufacturer.objects.all().count() self.assertEqual(manufacturer_count, 1) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def setUp(self): self.serializer_data = {"make": "Ford", "model": "Mustang"} self.external_API_Response = { "Count": 431, "Message": "Response returned successfully", "SearchCriteria": "Make:ford", "Results": [{ "Make_ID": 474, "Make_Name": "FORD", "Model_ID": 1861, "Model_Name": "Mustang" }, { "Make_ID": 474, "Make_Name": "FORD", "Model_ID": 1863, "Model_Name": "F-150" }] } self.manufacturer = Manufacturer.objects.create(make="Ford") self.car = Car.objects.create(manufacturer=self.manufacturer, model="Mustang") self.serializer = CarPostSerializer(self.car)
def test_save_not_existed_car_request(self): self.serializer_data["model"] = "unknown" with self.assertRaises(NotFound): serializer = CarPostSerializer(data=self.serializer_data) serializer.is_valid() with patch("cars.serializers.requests.get") as mock_get: mock_get.return_value.ok = False serializer.save()
def test_too_long_model_data(self): self.serializer_data["model"] = "t" * 151 serializer = CarPostSerializer(data=self.serializer_data) self.assertEqual(serializer.is_valid(), False) self.assertCountEqual(serializer.errors.keys(), ["model"])