Example #1
0
        public async Task Post_WhenCreateAVehicle_ShouldReturnsTheCreatedVehicle()
        {
            //Arrenge
            var newVehicleDescription = "VW Golf";
            var newVehiclePrice       = 10;

            _serviceMock.Setup(s => s.AddNewVehicle(It.IsAny <VehicleDto>()))
            .ReturnsAsync(new VehicleDto {
                Id = 1, Description = newVehicleDescription, PricePerDay = newVehiclePrice
            });

            var newVehicleRequest = new VehicleRequestModel
            {
                Description = newVehicleDescription,
                PricePerDay = newVehiclePrice
            };

            //Act
            var result = await _sut.Post(newVehicleRequest);

            //Assert
            result.Should().BeOfType(typeof(CreatedAtActionResult));
            var value = result.As <ObjectResult>().Value.As <VehicleResponseModel>();

            value.Id.Should().Be(1);
            value.Description.Should().Be(newVehicleDescription);
            value.PricePerDay.Should().Be(newVehiclePrice);

            _serviceMock.Verify(s => s.AddNewVehicle(It.Is <VehicleDto>(c => c.Description == newVehicleDescription &&
                                                                        c.PricePerDay == newVehiclePrice)), Times.Once);
        }
        public IHttpActionResult PostVehicle(VehicleRequestModel vehicle)
        {
            lock (locker)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                Vehicle v = new Vehicle();
                v.Model        = vehicle.Model;
                v.Description  = vehicle.Description;
                v.Manufactor   = vehicle.Manufactor;
                v.Year         = vehicle.Year;
                v.PricePerHour = vehicle.PricePerHour;
                var types = unitOfWork.VehicleTypes.GetAll();
                v.Type = (VehicleType)types.ToList <VehicleType>().Where(t => t.Name == vehicle.Type).ToList().First();
                //v.Images = vehicle.Images;

                Service service = unitOfWork.Services.Get(vehicle.ServiceId);

                try
                {
                    unitOfWork.Vehicles.Add(v);
                    service.Vehicles.Add(v);
                    unitOfWork.Complete();

                    return(Ok(v.Id));
                }
                catch (Exception ex)
                {
                    return(NotFound());
                }
            }
        }
Example #3
0
        public IActionResult Post([FromBody] VehicleRequestModel request)
        {
            logger.LogInformation($"POST /api/vehicle reach with body: {request}");

            var response = vehicleService.Add(request);

            return(response.CreateResponse(this));
        }
Example #4
0
        public async Task <IActionResult> Post([FromBody] VehicleRequestModel vehicleRequest)
        {
            var vehicleDto      = _mapper.Map <VehicleDto>(vehicleRequest);
            var addedVehicleDto = await _service.AddNewVehicle(vehicleDto);

            var responseModel = _mapper.Map <VehicleResponseModel>(addedVehicleDto);

            return(CreatedAtAction(nameof(GetById), new { id = responseModel.Id }, responseModel));
        }
Example #5
0
        public void ShouldAddVehicle()
        {
            var vehicleRequestModel = new VehicleRequestModel {
                Brand = "brand", PricePerDay = 10, Year = 2021
            };

            var response = vehicleService.Add(vehicleRequestModel);

            vehicleRepositoryMock.Verify(x => x.Add(It.IsAny <Vehicle>()), Times.Once);
            repositoryMock.Verify(x => x.Save(), Times.Once);
            Assert.False(response.HasErrors());
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.VEHICLE_SAVED), 1);
        }
Example #6
0
        public void ShouldValidateModel()
        {
            var vehicleRequestModel = new VehicleRequestModel {
                Brand = "", PricePerDay = null, Year = 2021
            };

            var response = vehicleService.Add(vehicleRequestModel);

            vehicleRepositoryMock.Verify(x => x.Add(It.IsAny <Vehicle>()), Times.Never);
            Assert.True(response.HasErrors());
            Assert.AreEqual(response.Messages.Count(x => x.Type == MessageType.Error), 2);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.BRAND_EMPTY), 1);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.PRICE_PER_DAY_INVALID), 1);
        }
Example #7
0
        public async Task GivenThereIsAVehicleWithPrice(string description, Decimal price)
        {
            var vehicleRequest = new VehicleRequestModel()
            {
                Description = description,
                PricePerDay = price
            };

            var response = await _client.PostAsJsonAsync("api/vehicles", vehicleRequest);

            response.StatusCode.Should().Be(HttpStatusCode.Created);
            var registeredVehicle = JsonConvert.DeserializeObject <VehicleResponseModel>(await response.Content.ReadAsStringAsync());

            registeredVehicle.Id.Should().BeGreaterThan(0);
            registeredVehicle.Description.Should().Be(description);
            registeredVehicle.PricePerDay.Should().Be(price);
        }
        public IHttpActionResult PutVehicle(int id, VehicleRequestModel vehicle)
        {
            lock (locker)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                if (id != vehicle.Id)
                {
                    return(BadRequest());
                }

                try
                {
                    var     vs = unitOfWork.Vehicles.GetAll();
                    Vehicle v  = vs.ToList <Vehicle>().Where(ve => ve.Id == id).ToList().First();
                    v.Id           = id;
                    v.Model        = vehicle.Model;
                    v.Description  = vehicle.Description;
                    v.Manufactor   = vehicle.Manufactor;
                    v.Year         = vehicle.Year;
                    v.PricePerHour = vehicle.PricePerHour;
                    var types = unitOfWork.VehicleTypes.GetAll();
                    v.Type = (VehicleType)types.ToList <VehicleType>().Where(t => t.Name == vehicle.Type).ToList().First();
                    //v.Images = vehicle.Images;

                    unitOfWork.Vehicles.Update(v);
                    unitOfWork.Complete();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!VehicleExists(id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(StatusCode(HttpStatusCode.NoContent));
            }
        }
Example #9
0
        public void ShouldNotSave()
        {
            repositoryMock.Setup(x => x.Save()).Throws(new Exception());

            var vehicleRequestModel = new VehicleRequestModel {
                Brand = "brand", PricePerDay = 10, Year = 2021
            };

            var response = vehicleService.Add(vehicleRequestModel);

            vehicleRepositoryMock.Verify(x => x.Add(It.IsAny <Vehicle>()), Times.Once);
            repositoryMock.Verify(x => x.Save(), Times.Once);

            Assert.True(response.HasErrors());
            Assert.AreEqual(response.Messages.Count(x => x.Type == MessageType.Error), 1);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.GENERAL_ERROR), 1);
        }
Example #10
0
        /// <summary>
        /// Create new vehicle
        /// </summary>
        /// <param name="request"></param>
        public Response Add(VehicleRequestModel request)
        {
            var response = new Response();

            logger.LogInformation("Starting request validation");

            if (string.IsNullOrWhiteSpace(request.Brand))
            {
                response.AddError(Constants.BRAND_EMPTY, "The field brand is required");
            }
            if (!request.PricePerDay.HasValue || request.PricePerDay <= 0)
            {
                response.AddError(Constants.PRICE_PER_DAY_INVALID, "The field pricePerDay is required");
            }

            if (response.HasErrors())
            {
                return(response);
            }

            logger.LogInformation("Request validated success");

            try
            {
                var domain = new Vehicle {
                    Brand = request.Brand, Year = request.Year, PricePerDay = request.PricePerDay.Value, Active = true
                };

                logger.LogInformation("Calling vehicle repository to save new vehicle");

                repository.VehicleRepository.Add(domain);
                repository.Save();

                response.AddSuccess(Constants.VEHICLE_SAVED, "Vehicle added succesfully");
            }
            catch (Exception e)
            {
                ExceptionUtils.HandleGeneralError(response, logger, e);
            }

            return(response);
        }
Example #11
0
        /// <summary>
        /// convert order car to vehicle request model.
        /// </summary>
        /// <param name="car"></param>
        /// <returns></returns>
        public static VehicleRequestModel Convert(OrderCarModel car)
        {
            VehicleRequestModel result = null;

            if (car != null)
            {
                List <BaoYangVehicleFivePropertyModel> propertiesList = null;
                if (car.ExtCol != null &&
                    car.ExtCol.ContainsKey("Properties") &&
                    car.ExtCol["Properties"] != null)
                {
                    string         properties = car.ExtCol["Properties"].ToString();
                    List <dynamic> list       = JsonConvert.DeserializeObject <List <dynamic> >(properties);
                    propertiesList = list.Select(o => new BaoYangVehicleFivePropertyModel()
                    {
                        Property      = o.propertyKey,
                        PropertyValue = o.propertyValue
                    }).ToList();
                }

                DateTime?onRoadTime = null;
                if (car.OnRoadYear > 0 && car.OnRoadYear < 9999 &&
                    car.OnRoadMonth > 0 && car.OnRoadMonth <= 12)
                {
                    onRoadTime = new DateTime(car.OnRoadYear.Value, car.OnRoadMonth.Value, 1);
                }

                result = new VehicleRequestModel()
                {
                    VehicleId  = car.VehicleId,
                    PaiLiang   = car.PaiLiang,
                    Nian       = car.Nian,
                    Tid        = car.Tid,
                    Properties = propertiesList,
                    OnRoadTime = onRoadTime,
                    Distance   = car.Distance
                };
            }

            return(result);
        }