public void WhenAddingReminder_ThenUpdatesServiceReminder()
        {
            const int newReminderId = 456;

            var vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" };

            _vehicleRepository
                .Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
                .Returns(vehicle);

            _reminderRepository
                .Setup(r => r.Create(DefaultVehicleId, It.IsAny<Reminder>()))
                .Callback(new Action<int, Reminder>((vehicleId, reminder) =>
                                                        {
                                                            // represents the entity created internally
                                                            reminder.ReminderId = newReminderId;
                                                            reminder.VehicleId = DefaultVehicleId;
                                                        }));

            var formModel = new ReminderFormModel();

            var handler = new AddReminderToVehicle(_vehicleRepository.Object, _reminderRepository.Object);
            handler.Execute(DefaultUserId, DefaultVehicleId, formModel);

            Assert.Equal(newReminderId, formModel.ReminderId);
            Assert.Equal(DefaultVehicleId, formModel.VehicleId);
        }
 public ImminentReminderModel(Vehicle vehicle, Reminder reminder, bool isOverdue)
 {
     IsOverdue = isOverdue;
     _vehicle = vehicle;
     _reminder = reminder;
     _summary = new ReminderSummaryModel(reminder);
 }
        public void WhenAddingReminder_ThenDelegatesToReminderRepository()
        {
            var vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" };

            _vehicleRepository
                .Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
                .Returns(vehicle);

            var handler = new AddReminderToVehicle(_vehicleRepository.Object, _reminderRepository.Object);
            handler.Execute(DefaultUserId, DefaultVehicleId, new ReminderFormModel());

            _reminderRepository
                .Verify(r => r.Create(DefaultVehicleId, It.IsAny<Reminder>()), Times.Once());
        }
        public void WhenVehicleAdded_ThenUpdatesRepository()
        {
            var repository = new VehicleRepository();
            var initialCount = repository.All().Count();

            var vehicle = new Vehicle {Name = "Vehicle"};

            repository.Create(defaultTestUser.UserId, vehicle);

            var actualList = new VehicleRepository().All().ToList();

            Assert.Equal(initialCount + 1, actualList.Count);
            Assert.Equal(vehicle.Name, actualList[initialCount].Name);
        }
        public void ForOtherUser_ThenNullReturned()
        {
            const int notTheCurrentUserId = UserId + 1;

            var vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" };

            _vehicleRepo
                .Setup(vr => vr.GetVehicle(notTheCurrentUserId, DefaultVehicleId))
                .Returns((Vehicle)null);

            var handler = new GetVehicleById(_vehicleRepo.Object, _fillupRepo.Object);
            var retrievedVehicle = handler.Execute(notTheCurrentUserId, vehicle.VehicleId);

            Assert.Null(retrievedVehicle);
        }
        public void ThenVehicleReturned()
        {
            var vehicle = new Vehicle { VehicleId = 1, Name = "vehicle" };

            _vehicleRepo
                .Setup(vr => vr.GetVehicle(UserId, vehicle.VehicleId))
                .Returns(vehicle);

            var handler = new GetVehicleById(_vehicleRepo.Object, _fillupRepo.Object);

            var retrievedVehicle = handler.Execute(UserId, vehicle.VehicleId);

            Assert.NotNull(retrievedVehicle);
            Assert.Equal("vehicle", retrievedVehicle.Name);
        }
        public void WhenCanAddReminder_ThenReturnsEmptyCollection()
        {
            var vehicle1 = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle1" };

            _vehicleRepositoryMock
                .Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
                .Returns(vehicle1);

            var handler = new CanAddReminder(_vehicleRepositoryMock.Object, _fillupRepo.Object);

            var formModel = new ReminderFormModel { VehicleId = DefaultVehicleId, Title = "Test", DueDistance = 20000 };

            var result = handler.Execute(DefaultUserId, formModel);

            Assert.Empty(result);
        }
        public void ThenVehiclePhotoIdSet()
        {
            const int photoId = 99;

            var vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle", PhotoId = photoId };

            _vehicleRepo
                .Setup(vr => vr.GetVehicle(UserId, DefaultVehicleId))
                .Returns(vehicle);

            var handler = new GetVehicleById(_vehicleRepo.Object, _fillupRepo.Object);

            var retrievedVehicle = handler.Execute(UserId, vehicle.VehicleId);

            Assert.Equal(photoId, retrievedVehicle.PhotoId);
        }
        public void WhenGetFleetSummaryStatistics_CalculatesAcrossVehicles()
        {
            var fillups1 = new[]
                            {
                                new FillupEntry {Date = DateTime.UtcNow.AddDays(-1), PricePerUnit = 1.0, TotalUnits = 10},
                                new FillupEntry {Date = DateTime.UtcNow, PricePerUnit = 1.0, TotalUnits = 10}
                            };

            var fillups2 = new[]
                            {
                                new FillupEntry {Date = DateTime.UtcNow.AddDays(-1), PricePerUnit = 1.0, TotalUnits = 10},
                                new FillupEntry {Date = DateTime.UtcNow, PricePerUnit = 1.0, TotalUnits = 10},
                                new FillupEntry
                                    {
                                        Date = DateTime.UtcNow,
                                        PricePerUnit = 1.0,
                                        TotalUnits = 10,
                                        TransactionFee = 5.0
                                    }
                            };

            var vehicle1 = new Vehicle { VehicleId = 1 };
            var vehicle2 = new Vehicle { VehicleId = 2 };

            var mockVehicleRepository = new Mock<IVehicleRepository>();
            var mockFillupsRepository = new Mock<IFillupRepository>();

            mockVehicleRepository
                .Setup(x => x.GetVehicles(DefaultUserId))
                .Returns(new[] { vehicle1, vehicle2 });

            mockFillupsRepository
                .Setup(x => x.GetFillups(vehicle1.VehicleId))
                .Returns(fillups1);

            mockFillupsRepository
                .Setup(x => x.GetFillups(vehicle2.VehicleId))
                .Returns(fillups2);

            var handler = new GetFleetSummaryStatistics(mockVehicleRepository.Object,mockFillupsRepository.Object);

            var actual = handler.Execute(DefaultUserId);

            Assert.NotNull(actual);
            Assert.Equal(30, actual.TotalFuelCost);
            Assert.Equal(35, actual.TotalCost);
        }
        public void ThenUpdatesSortOrderForEachVehicle()
        {
            var vehicleOne = new Vehicle {VehicleId = 1, Name = "oldName", SortOrder = 0};
            var vehicleTwo = new Vehicle {VehicleId = 2, Name = "oldName", SortOrder = 1};
            var vehicleThree = new Vehicle {VehicleId = 3, Name = "oldName", SortOrder = 2};

            _vehicleRepo.Setup(vr => vr.GetVehicle(It.IsAny<int>(), 1)).Returns(vehicleOne);
            _vehicleRepo.Setup(vr => vr.GetVehicle(It.IsAny<int>(), 2)).Returns(vehicleTwo);
            _vehicleRepo.Setup(vr => vr.GetVehicle(It.IsAny<int>(), 3)).Returns(vehicleThree);

            var newOrder = new[] {3, 2, 1};
            var handler = new UpdateVehicleSortOrder(_vehicleRepo.Object);
            handler.Execute(UserId, newOrder);

            Assert.Equal(2, vehicleOne.SortOrder);
            Assert.Equal(1, vehicleTwo.SortOrder);
            Assert.Equal(0, vehicleThree.SortOrder);
        }
        public void ThenDelegatesToVehicleRepositoryForEachVehicle()
        {
            var vehicleOne = new Vehicle {VehicleId = 1, Name = "oldName", SortOrder = 0};
            var vehicleTwo = new Vehicle {VehicleId = 2, Name = "oldName", SortOrder = 1};
            var vehicleThree = new Vehicle {VehicleId = 3, Name = "oldName", SortOrder = 2};

            _vehicleRepo.Setup(r => r.GetVehicle(It.IsAny<int>(), 1)).Returns(vehicleOne);
            _vehicleRepo.Setup(r => r.GetVehicle(It.IsAny<int>(), 2)).Returns(vehicleTwo);
            _vehicleRepo.Setup(r => r.GetVehicle(It.IsAny<int>(), 3)).Returns(vehicleThree);

            var newOrder = new[] {3, 2, 1};

            var handler = new UpdateVehicleSortOrder(_vehicleRepo.Object);
            handler.Execute(UserId, newOrder);

            _vehicleRepo.Verify(r => r.Update(vehicleOne), Times.Once());
            _vehicleRepo.Verify(r => r.Update(vehicleTwo), Times.Once());
            _vehicleRepo.Verify(r => r.Update(vehicleThree), Times.Once());
        }
        private void CalculateSeriesForVehicle(Vehicle vehicle, StatisticSeries series, DateTime? startDate, DateTime? endDate)
        {
            Debug.Assert(series != null);

            DateTime startFilterDate = startDate ?? DateTime.MinValue;
            DateTime endFilterDate = endDate ?? DateTime.UtcNow;

            var fillUps = _fillupRepository.GetFillups(vehicle.VehicleId);

            var fillupGroups = from fillUp in fillUps
                               where ((fillUp.Date >= startFilterDate) && (fillUp.Date <= endFilterDate))
                               group fillUp by new { Year = fillUp.Date.Year, Month = fillUp.Date.Month }
                                   into g
                                   orderby g.Key.Year, g.Key.Month
                                   select g;

            var firstFillUp = fillUps.OrderBy(x => x.Date).FirstOrDefault();

            VehicleStatisticsModel statistics;
            foreach (var fillupGroup in fillupGroups)
            {
                var includeFirstFillup = (fillupGroup.Key.Year != firstFillUp.Date.Year) ||
                                                    (fillupGroup.Key.Month != firstFillUp.Date.Month);

                statistics = CalculateStatistics.Calculate(fillupGroup, includeFirstFillup);

                Debug.Assert(firstFillUp != null);
                

                var seriesEntry = new StatisticSeriesEntry
                {
                    Id = vehicle.VehicleId,
                    Name = vehicle.Name,
                    Year = fillupGroup.Key.Year,
                    Month = fillupGroup.Key.Month,
                    AverageFuelEfficiency = Math.Round(statistics.AverageFuelEfficiency, 2),
                    TotalCost = Math.Round(statistics.TotalCost, 2),
                    TotalDistance = statistics.TotalDistance,
                };
                series.Entries.Add(seriesEntry);
            }            
        }
        private void InitializeFixture()
        {
            defaultTestUser = new User()
                                       {
                                           AuthorizationId = "TestAuthorizationId",
                                           DisplayName = "DefaultTestUser"
                                       };

            var userRepository = new UserRepository();
            userRepository.Create(defaultTestUser);

            int userId = defaultTestUser.UserId;

            var vehicleRepository = new VehicleRepository();
            defaultVehicle = new Vehicle()
                                      {
                                          Name = "Test Vehicle"
                                      };
            vehicleRepository.Create(defaultTestUser.UserId, defaultVehicle);
        }
        public void ByUserIdForUser_ThenReturnsVehiclesInSortedOrder()
        {
            var vehicle01 = new Vehicle { Name = "first", VehicleId = 4, SortOrder = 1 };
            var vehicle02 = new Vehicle { Name = "second", VehicleId = 1, SortOrder = 3 };
            var vehicle03 = new Vehicle { Name = "third", VehicleId = 2, SortOrder = 2 };

            var vehicles = new List<Vehicle> { vehicle03, vehicle02, vehicle01 };

            _vehicleRepo
                .Setup(vr => vr.GetVehicles(UserId))
                .Returns(vehicles);

            var handler = new GetVehicleListForUser(_vehicleRepo.Object, _fillupRepo.Object);

            var result = handler.Execute(UserId);
            var acutal = result.ToArray();

            Assert.Equal(vehicle01.Name, acutal[0].Name);
            Assert.Equal(vehicle03.Name, acutal[1].Name);
            Assert.Equal(vehicle02.Name, acutal[2].Name);
        }
        public static Vehicle ConvertToEntity(this ICreateVehicleCommand vehicleForm, int userId, bool includeVehicleId = false)
        {
            if (vehicleForm == null)
            {
                return null;
            }

            var vehicle = new Vehicle
                              {
                                  MakeName = vehicleForm.MakeName,
                                  ModelName = vehicleForm.ModelName,
                                  Name = vehicleForm.Name,
                                  SortOrder = vehicleForm.SortOrder,
                                  Year = vehicleForm.Year,
                                  UserId = userId
                              };

            if (includeVehicleId) vehicle.VehicleId = vehicleForm.VehicleId;

            return vehicle;
        }
        public void WhenVehicleAdded_ThenPersists()
        {
            int userId = this.defaultTestUser.UserId;
            var repository = new VehicleRepository();

            Vehicle vehicle1 = new Vehicle {Name = "Vehicle1"};
            Vehicle vehicle2 = new Vehicle {Name = "Vehicle2"};

            repository.Create(userId, vehicle1);
            repository.Create(userId, vehicle2);

            // I use a new context and repository to verify the data was stored
            var repository2 = new VehicleRepository();

            var retrievedVehicles = repository2.GetVehicles(userId);

            Assert.NotNull(retrievedVehicles);
            List<Vehicle> actualList = new List<Vehicle>(retrievedVehicles);

            Assert.Equal(2, actualList.Count);
            Assert.Equal(vehicle1.Name, actualList[0].Name);
            Assert.Equal(vehicle2.Name, actualList[1].Name);
        }
        public void WhenCanAddReminderWithInvalidDueDistance_ThenReturnsValidationResult()
        {
            var vehicle1 = new Vehicle
                               {
                                   VehicleId = DefaultVehicleId,
                                   Name = "vehicle1"
                               };

            _vehicleRepositoryMock
                .Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId))
                .Returns(vehicle1);

            _fillupRepo
                .Setup(r => r.GetFillups(DefaultVehicleId))
                .Returns(new[] {new FillupEntry {Odometer = 7000}});

            var handler = new CanAddReminder(_vehicleRepositoryMock.Object, _fillupRepo.Object);

            var formModel = new ReminderFormModel { VehicleId = DefaultVehicleId, Title = "Test", DueDistance = 5000 };

            var result = handler.Execute(DefaultUserId, formModel);

            Assert.NotEmpty(result);
        }
        public void WhenVehicleDeleted_ThenPersists()
        {
            int userId = this.defaultTestUser.UserId;
            var repository = new VehicleRepository();

            Vehicle vehicle1 = new Vehicle {Name = "Vehicle1"};
            repository.Create(userId, vehicle1);

            var retrievedVehicles = repository.GetVehicles(userId);
            Assert.Equal(1, retrievedVehicles.Count());
            repository.Delete(retrievedVehicles.First().VehicleId);

            // I use a new context and repository to verify the vehicle was deleted
            var repository2 = new VehicleRepository();

            var verifyVehicles = repository2.GetVehicles(userId);

            Assert.NotNull(retrievedVehicles);
            Assert.Equal(0, verifyVehicles.Count());
        }
        public void WhenGettingOtherUsersVehicle_ThenReturnsNull()
        {
            int userId = defaultTestUser.UserId;
            var repository = new VehicleRepository();
            const int unknownId = 4200;

            var vehicle = new Vehicle {Name = "Vehicle"};

            repository.Create(userId, vehicle);

            var repositoryForVerify = new VehicleRepository();
            Assert.Null(repositoryForVerify.GetVehicle(unknownId, vehicle.VehicleId));
        }
        public void WhenVehicleModifiedInSameContext_ThenPersistsChange()
        {
            int userId = this.defaultTestUser.UserId;
            var repository = new VehicleRepository();

            Vehicle vehicle = new Vehicle {Name = "Vehicle", UserId = userId};
            repository.Create(userId, vehicle);

            // I use a new context and repository to verify the data was stored
            var repositoryForUpdate = new VehicleRepository();

            var retrievedVehicle = repositoryForUpdate.GetVehicles(userId).First();

            retrievedVehicle.Name = "Updated Vehicle Name";
            repositoryForUpdate.Update(retrievedVehicle);
            int updatedVehicleId = retrievedVehicle.VehicleId;

            var repositoryForVerify = new VehicleRepository();
            var updatedVehicle = repositoryForVerify.GetVehicle(userId, updatedVehicleId);

            Assert.Equal("Updated Vehicle Name", updatedVehicle.Name);
        }
        public void WhenVehicleAdded_ThenUpdatesVehicleId()
        {
            const int userId = 999;
            var repository = new VehicleRepository();

            var vehicle = new Vehicle {Name = "Vehicle"};

            repository.Create(userId, vehicle);

            var retrievedVehicles = repository.GetVehicles(userId);

            Assert.NotNull(retrievedVehicles);
            var actualList = new List<Vehicle>(retrievedVehicles);

            Assert.Equal(1, actualList.Count);
            Assert.Equal(vehicle.VehicleId, actualList[0].VehicleId);
        }
 public VehicleModel(Vehicle vehicle, VehicleStatisticsModel statistics)
 {
     Vehicle = vehicle;
     Statistics = statistics;
 }
 public WhenAddingFillup()
 {
     _vehicleRepo = new Mock<IVehicleRepository>();
     _fillupRepositoryMock = new Mock<IFillupRepository>();
     _vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" };
 }
        private void CreateFillups(Vehicle vehicle, FillupData data)
        {
            int odometer = data.Mileage;
            DateTime date = data.Date;
            Double unitsModifier = data.Units;
            Double distanceModifier = data.Distance;
            int[] randomArray = RandomizeArray(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11});
            int currentIndex = 0;
            var random = new Random();
            bool isFirst = true;
            while (date < DateTime.Now)
            {
                int dataIndex = randomArray[currentIndex];
                var distance = (int) (_distance[dataIndex]*distanceModifier);
                var fillup = new FillupEntry
                                 {
                                     Date = date,
                                     Odometer = odometer,
                                     PricePerUnit = _price[dataIndex],
                                     TotalUnits = _units[dataIndex]*unitsModifier,
                                     TransactionFee = _fee[dataIndex],
                                     VehicleId = vehicle.VehicleId,
                                     Vendor = _vendor[dataIndex]
                                 };
                if (isFirst)
                {
                    isFirst = false;
                    fillup.Distance = null;
                }
                else
                {
                    fillup.Distance = distance;
                }
                odometer += distance;

                currentIndex += 1;
                if (currentIndex > 11)
                {
                    currentIndex = 0;
                }
                date = date.AddDays(random.Next(3, 14));
                _fillups.Create(vehicle.UserId, vehicle.VehicleId, fillup);
            }
        }
        private void CreateReminders(Vehicle vehicle)
        {
            var lastFillup = _fillups.GetFillups(vehicle.VehicleId).OrderByDescending(f => f.Date).FirstOrDefault();
            if (lastFillup == null)
            {
                return;
            }

            // create "overdue by mileage" reminder
            vehicle.Reminders.Add(new Reminder
                           {
                               DueDate = null,
                               DueDistance = lastFillup.Odometer - 10,
                               IsFulfilled = false,
                               Remarks = "Check air filter when oil is changed",
                               Title = "Oil Change",
                               VehicleId = vehicle.VehicleId
                           });

            // create "overdue by date" reminder
            vehicle.Reminders.Add(new Reminder
                           {
                               DueDate = lastFillup.Date.AddDays(-10),
                               DueDistance = null,
                               IsFulfilled = false,
                               Remarks = "Check condition of the wipers",
                               Title = "Check Wiper Fluid",
                               VehicleId = vehicle.VehicleId
                           });

            // create "to be done soon by mileage" reminder
            vehicle.Reminders.Add(new Reminder
                           {
                               DueDate = null,
                               DueDistance = lastFillup.Odometer + 400,
                               IsFulfilled = false,
                               Remarks = "Check air pressure",
                               Title = "Rotate Tires",
                               VehicleId = vehicle.VehicleId
                           });

            // create "to be done soon by date" reminder
            vehicle.Reminders.Add(new Reminder
                           {
                               DueDate = DateTime.Now.AddDays(+10),
                               DueDistance = null,
                               IsFulfilled = false,
                               Remarks = "Check air freshener",
                               Title = "Vacuum Car",
                               VehicleId = vehicle.VehicleId
                           });

            vehicle.Reminders.ToList()
                .ForEach(reminder => _reminders.Create(vehicle.VehicleId,reminder));
        }
        private void CreateVehicle(int userId, Vehicle vehicle)
        {
            _vehicles.Create(userId, vehicle);

            string photoId = string.Format("MileageStats.Data.InMemory.Photos.{0}.jpg", vehicle.MakeName);
            var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(photoId);
            vehicle.Photo = CreateVehiclePhoto(Image.FromStream(stream), vehicle.VehicleId);
            vehicle.PhotoId = vehicle.Photo.VehiclePhotoId;
        }
        public void WhenGettingVehicle_ThenVehicleStatisticsReturned()
        {
            var fillups = new List<FillupEntry>
                              {
                                  new FillupEntry
                                      {
                                          Date = DateTime.UtcNow.AddDays(-10),
                                          Odometer = 500,
                                          PricePerUnit = 10.0,
                                          TotalUnits = 10.0
                                      },
                                  new FillupEntry
                                      {
                                          Date = DateTime.UtcNow.AddDays(-5),
                                          Odometer = 1000,
                                          PricePerUnit = 10.0,
                                          TotalUnits = 10.0
                                      }
                              };

            var vehicle = new Vehicle { VehicleId = DefaultVehicleId };

            _vehicleRepo
                .Setup(vr => vr.GetVehicle(UserId, DefaultVehicleId))
                .Returns(vehicle);

            _fillupRepo
                .Setup(r => r.GetFillups(DefaultVehicleId))
                .Returns(fillups);

            var handler = new GetVehicleById(_vehicleRepo.Object, _fillupRepo.Object);
            var retrievedVehicle = handler.Execute(UserId, vehicle.VehicleId);

            Assert.NotNull(retrievedVehicle);
            Assert.Equal(1000, retrievedVehicle.Odometer);
        }