Ejemplo n.º 1
0
        public void CreateDataSet()
        {
            var options = new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                          .UseInMemoryDatabase(nameof(EuGatewayServiceUploadTest))
                          .Options;

            _dbContext = new DigNDB_SmittestopContext(options);
            _dbContext.Database.EnsureDeleted();

            _temporaryExposureKeyRepositoryLogger = new Mock <ILogger <TemporaryExposureKeyRepository> >(MockBehavior.Loose);
            _loggerGatewayWebContextReader        = new Mock <ILogger <GatewayWebContextReader> >();
            var translationsRepositoryMock = new Mock <IGenericRepository <Translation> >(MockBehavior.Strict);

            _countryRepository = new CountryRepository(_dbContext, translationsRepositoryMock.Object, new AppSettingsConfig());
            _autoMapper        = CreateAutoMapperWithDependencies(_countryRepository);

            _config = new EuGatewayConfig()
            {
                AuthenticationCertificateFingerprint = "AuthenticationCertificateFingerprint",
                SigningCertificateFingerprint        = "SigningCertificateFingerprint",
                Url = "http://netcompany.pl",
            };

            _epochConverter = new EpochConverter();

            _denmark = TestCountryBuilder.Denmark.Build();
            _poland  = TestCountryBuilder.Poland.Build();
            _germany = TestCountryBuilder.Germany.Build();
            _latviaDisabledDownload = TestCountryBuilder.Latvia
                                      .SetIsPullingFromGatewayEnabled(false)
                                      .Build();

            _dbContext.AddRange(_denmark, _poland, _germany, _latviaDisabledDownload);
            _dbContext.SaveChanges();
        }
        public static void InitializeDbForTests(DigNDB_SmittestopContext db)
        {
            var tokens = GetTokens();

            db.JwtToken.AddRange(tokens);
            db.SaveChanges();
        }
        public void CreateDataSet()
        {
            var options = new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                          .UseInMemoryDatabase(nameof(EuGatewayServiceUploadTest))
                          .Options;

            _dbContext = new DigNDB_SmittestopContext(options);
            _dbContext.Database.EnsureDeleted();

            _config = new EuGatewayConfig()
            {
                AuthenticationCertificateFingerprint = "AuthenticationCertificateFingerprint",
                SigningCertificateFingerprint        = "SigningCertificateFingerprint",
                Url = "http://netcompany.pl",
            };

            _denmark = TestCountryBuilder.Denmark.Build();
            _poland  = TestCountryBuilder.Poland.Build();
            _germany = TestCountryBuilder.Germany.Build();
            _latvia  = TestCountryBuilder.Latvia.Build();

            _dbContext.AddRange(new Country[] { _denmark, _poland, _germany, _latvia });
            _dbContext.SaveChanges();

            _originCountry = _denmark;
        }
Ejemplo n.º 4
0
        public void TestInsert()
        {
            var context = new DigNDB_SmittestopContext(_options);

            context.Database.EnsureDeleted();

            var genericRepository = new GenericRepository <TemporaryExposureKey>(context);

            var entity = new TemporaryExposureKey
            {
                Id                    = Guid.NewGuid(),
                CreatedOn             = DateTime.Now,
                KeyData               = new byte[] { 1, 2, 3 },
                RollingPeriod         = 123,
                RollingStartNumber    = 123,
                TransmissionRiskLevel = RiskLevel.RISK_LEVEL_LOW
            };

            genericRepository.Insert(entity);
            context.SaveChanges();

            var retrievedEntity = context.TemporaryExposureKey.Find(entity.Id);

            Assert.AreEqual(retrievedEntity, entity);
        }
Ejemplo n.º 5
0
        public void TestDelete()
        {
            var expectDate = DateTime.UtcNow;
            var entities   = CreateMockedListExposureKeys(expectDate, 2);

            using DigNDB_SmittestopContext context = CreatePopulatedContext(entities);
            var genericRepository = new GenericRepository <TemporaryExposureKey>(context);

            var firstEntity = entities.First();

            context.Entry(firstEntity).State = EntityState.Detached;
            context.SaveChanges();
            genericRepository.Delete(firstEntity);
            context.SaveChanges();

            var retrievedEntity = genericRepository.GetById(firstEntity.Id);

            Assert.AreEqual(retrievedEntity, null);
        }
Ejemplo n.º 6
0
        private DigNDB_SmittestopContext CreatePopulatedContext <T>(IEnumerable <T> entities)
            where T : class
        {
            var context = new DigNDB_SmittestopContext(_options);

            context.Database.EnsureDeleted();
            context.AddRange(entities);
            context.SaveChanges();

            return(context);
        }
Ejemplo n.º 7
0
        public void SetUp()
        {
            GenerateData();
            DbContextOptions <DigNDB_SmittestopContext> options =
                new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                .UseInMemoryDatabase(nameof(ApplicationStatisticsRepositoryTests)).Options;

            _context = new DigNDB_SmittestopContext(options);
            _context.Database.EnsureDeleted();
            _context.AddRange(_covidStatisticsMockData);
            _context.SaveChanges();
        }
Ejemplo n.º 8
0
        public void GetEntryByDate_EntryExists_EntryIsReturned()
        {
            // Arrange
            var expectedResult = new CovidStatistics()
            {
                Id        = 5,
                EntryDate = _exampleDate
            };

            _covidStatisticsMockData.Add(expectedResult);
            _context.Add(expectedResult);
            _context.SaveChanges();
            var      covidStatisticsRepository = CreateCovidStatisticsRepository();
            DateTime date = _exampleDate;

            // Act
            var result = covidStatisticsRepository.GetEntryByDate(
                date);

            // Assert
            Assert.AreEqual(expectedResult, result);
        }
Ejemplo n.º 9
0
        public void RemoveKeyDuplicates_ShouldOnlyWorkOnKeysCreatedUpTo14DaysAgo()
        {
            var options = new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                          .UseInMemoryDatabase(nameof(EuGatewayServiceUploadTest))
                          .Options;

            var dbContext = new DigNDB_SmittestopContext(options);

            dbContext.Database.EnsureDeleted();
            var translationsRepositoryMock = new Mock <IGenericRepository <Translation> >(MockBehavior.Strict);

            var originSpecificSettings = new AppSettingsConfig()
            {
                OriginCountryCode = "dk"
            };
            var countryRepository = new CountryRepository(dbContext, translationsRepositoryMock.Object, originSpecificSettings);
            var keysRepository    = new TemporaryExposureKeyRepository(dbContext, countryRepository);

            _keyFilter = new KeyFilter(_keyMapper, _keyValidator.Object, new ExposureKeyMapper(), _logger.Object, keysRepository);

            var rollingStartNumberNewerThan14Days = DateTimeOffset.Now.Subtract(new TimeSpan(DaysOffset - 1, 0, 0, 0)).ToUnixTimeSeconds();
            var rollingStartNumberOlderThan14Days = DateTimeOffset.Now.Subtract(new TimeSpan(DaysOffset + 3, 0, 0, 0)).ToUnixTimeSeconds();
            var origin = new Country {
                Id = 1
            };
            var keysNewerThan14Days = new List <TemporaryExposureKey>
            {
                new TemporaryExposureKey {
                    Id = Guid.NewGuid(), RollingStartNumber = rollingStartNumberNewerThan14Days, Origin = origin, KeyData = new byte[] { 1 }
                },
            };
            var keysOlderThan14Days = new List <TemporaryExposureKey>
            {
                new TemporaryExposureKey {
                    Id = Guid.NewGuid(), RollingStartNumber = rollingStartNumberOlderThan14Days, Origin = origin, KeyData = new byte[] { 2 }
                },
                new TemporaryExposureKey {
                    Id = Guid.NewGuid(), RollingStartNumber = rollingStartNumberOlderThan14Days, Origin = origin, KeyData = new byte[] { 3 }
                },
            };
            var keyList = keysNewerThan14Days.Concat(keysOlderThan14Days).ToList();

            dbContext.TemporaryExposureKey.AddRange(keyList);
            dbContext.SaveChanges();

            var filteredList = _keyFilter.RemoveKeyDuplicatesAsync(keyList).Result;

            filteredList.Count.Should().Be(keysOlderThan14Days.Count);
        }
        public void GetAll_HaveData_ShouldReturnCorrectNumberOfRecord()
        {
            var expectKeys = 4;
            var data       = CreateMockedListExposureKeys(DateTime.UtcNow, expectKeys, true);

            using (var context = new DigNDB_SmittestopContext(_options))
            {
                context.Database.EnsureDeleted();
                //add data to context
                context.TemporaryExposureKey.AddRange(data);
                context.SaveChanges();
                _repo = new TemporaryExposureKeyRepository(context, _countryRepository.Object);
                var keys = _repo.GetAll().Result;
                Assert.AreEqual(expectKeys, keys.Count);
            }
        }
        public void GetAllKeyData_HaveData_ShouldReturnCorrectResult()
        {
            var data           = CreateMockedListExposureKeys(DateTime.UtcNow, 4, true);
            var expectKeysData = data.Select(x => x.KeyData).ToList();

            using (var context = new DigNDB_SmittestopContext(_options))
            {
                context.Database.EnsureDeleted();
                //add data to context
                context.TemporaryExposureKey.AddRange(data);
                context.SaveChanges();
                _repo = new TemporaryExposureKeyRepository(context, _countryRepository.Object);
                var keys = _repo.GetAllKeyData().Result;
                CollectionAssert.AreEqual(expectKeysData, keys);
            }
        }
Ejemplo n.º 12
0
        public void TestEdit()
        {
            var expectDate = DateTime.UtcNow;
            var entities   = CreateMockedListExposureKeys(expectDate, 2);

            using DigNDB_SmittestopContext context = CreatePopulatedContext(entities);
            var genericRepository = new GenericRepository <TemporaryExposureKey>(context);

            var entity = entities.First();

            entity.RollingPeriod = 567;

            genericRepository.Edit(entity);
            context.SaveChanges();

            var retrievedEntity = context.TemporaryExposureKey.Find(entity.Id);

            Assert.AreEqual(retrievedEntity.RollingPeriod, 567);
        }
        public void GetById_HaveRecord_ShouldReturnCorrectRecord()
        {
            var data = CreateMockedListExposureKeys(DateTime.UtcNow, 4, true);

            using (var context = new DigNDB_SmittestopContext(_options))
            {
                context.Database.EnsureDeleted();
                context.TemporaryExposureKey.AddRange(data);
                context.SaveChanges();
                _repo = new TemporaryExposureKeyRepository(context, _countryRepository.Object);
                var expectKey = data[0];
                var actualKey = _repo.GetById(expectKey.Id).Result;

                Assert.AreEqual(expectKey.Id, actualKey.Id);
                Assert.AreEqual(expectKey.TransmissionRiskLevel, actualKey.TransmissionRiskLevel);
                Assert.AreEqual(expectKey.CreatedOn, actualKey.CreatedOn);
                Assert.AreEqual(expectKey.KeyData, actualKey.KeyData);
            }
        }
Ejemplo n.º 14
0
        public async Task GetNewestEntryAsync_EntriesExist_ShouldReturnNewestEntry()
        {
            // Arrange
            _context.AddRange(_appStatisticsMockData);
            _context.SaveChanges();
            var applicationStatisticsRepository = CreateApplicationStatisticsRepository();

            // Act
            var result = await applicationStatisticsRepository.GetNewestEntryAsync();

            // Assert
            var expected = _appStatisticsMockData[1];

            Assert.AreEqual(expected.EntryDate, result.EntryDate);
            Assert.AreEqual(expected.Id, result.Id);
            Assert.AreEqual(expected.PositiveResultsLast7Days, result.PositiveResultsLast7Days);
            Assert.AreEqual(expected.PositiveTestsResultsTotal, result.PositiveTestsResultsTotal);
            Assert.AreEqual(expected.SmittestopDownloadsTotal, result.SmittestopDownloadsTotal);
        }
        public void GetTemporaryExposureKeys_HaveRecord_ShouldReturnCorrectRecordMatchedRequirement()
        {
            var expectDate         = DateTime.UtcNow;
            var dataForCurrentDate = CreateMockedListExposureKeys(expectDate, 2, true);
            var dataForOtherDate   = CreateMockedListExposureKeys(expectDate.AddDays(-12), 3, true);
            var dataForNotDK       = CreateMockedListExposureKeys(expectDate.AddDays(-12), 3, false);

            using (var context = new DigNDB_SmittestopContext(_options))
            {
                context.Database.EnsureDeleted();
                //add data to context
                context.TemporaryExposureKey.AddRange(dataForCurrentDate);
                context.TemporaryExposureKey.AddRange(dataForOtherDate);
                context.TemporaryExposureKey.AddRange(dataForNotDK);
                context.SaveChanges();
                _repo = new TemporaryExposureKeyRepository(context, _countryRepository.Object);
                var keys = _repo.GetKeysOnlyFromApiOriginCountry(expectDate, 0);
                Assert.AreEqual(dataForCurrentDate.Count, keys.Count);
            }
        }
        private CountryRepository CreateCountryRepository(Country[] fakeCountries)
        {
            DbContextOptions <DigNDB_SmittestopContext> options =
                new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                .UseInMemoryDatabase(nameof(CountryRepositoryTests)).Options;
            var context = new DigNDB_SmittestopContext(options);

            context.Database.EnsureDeleted();

            fakeCountries[0].Code = ExampleCountryCodePl;
            fakeCountries[1].Code = ExampleCountryCodeDk;

            var exposureKeyCountries = new List <TemporaryExposureKeyCountry>
            {
                new TemporaryExposureKeyCountry
                {
                    CountryId = 1
                },
                new TemporaryExposureKeyCountry
                {
                    CountryId = 2
                },
            };

            context.AddRange(fakeCountries);
            context.AddRange(exposureKeyCountries);
            context.SaveChanges();

            var translationRepositoryMock = new Mock <IGenericRepository <Translation> >();

            IOriginSpecificSettings config = new AppSettingsConfig()
            {
                OriginCountryCode = ExampleCountryCodeDk
            };

            return(new CountryRepository(context, translationRepositoryMock.Object, config));
        }
 public void Save()
 {
     _context.SaveChanges();
 }
Ejemplo n.º 18
0
 public void UpdateKeysRollingStartField(List <TemporaryExposureKey> keys)
 {
     _dbContext.UpdateRange(keys);
     _dbContext.SaveChanges();
 }
        public void UploadKeysInMultipleBatches_shouldSendOnlyDkKeys(int batchSize)
        {
            // .: Setup
            // key data must be unique for verification methods
            var denmarkKeys_ApiV1 = TestTemporaryExposureKeyBuilder.CreateDefault(_denmark)
                                    .SetVisitedCountries(new[] { _germany, _poland })
                                    .SetKeySource(KeySource.SmitteStopApiVersion2)
                                    .SetRollingStartNumber(DateTime.UtcNow.AddDays(-1))
                                    .Build(new[] { "Dk_V1_1", "Dk_V1_2", "Dk_V1_3", "Dk_V1_4" });

            var denmarkKeys_ApiV2 = TestTemporaryExposureKeyBuilder.CreateDefault(_denmark)
                                    .SetVisitedCountries(new[] { _germany, _poland })
                                    .SetKeySource(KeySource.SmitteStopApiVersion3)
                                    .SetRollingStartNumber(DateTime.UtcNow.AddDays(-1))
                                    .SetDaysSinceOnsetOfSymptoms(10)
                                    .Build(new[] { "Dk_V2_1", "Dk_V2_2", "Dk_V2_3", "Dk_V2_4" });

            var denmarkKeys_ApiV2_InvalidDaysSinceOnsetOfSymptoms = TestTemporaryExposureKeyBuilder.CreateDefault(_denmark)
                                                                    .SetVisitedCountries(new[] { _germany, _poland })
                                                                    .SetKeySource(KeySource.SmitteStopApiVersion3)
                                                                    .SetRollingStartNumber(DateTime.UtcNow.AddDays(-1))
                                                                    .SetDaysSinceOnsetOfSymptoms(100)
                                                                    .Build(new[] { "Dk_V2_5", "Dk_V2_6", "Dk_V2_7", "Dk_V2_8" });

            var denmarkKeys_ApiV2_Old = TestTemporaryExposureKeyBuilder.CreateDefault(_denmark)
                                        .SetVisitedCountries(new[] { _germany, _poland })
                                        .SetKeySource(KeySource.SmitteStopApiVersion3)
                                        .SetRollingStartNumber(DateTime.UtcNow.AddDays(-16))
                                        .Build(new[] { "Dk_V2_Old_1", "Dk_V2_Old_2", "Dk_V2_Old_3", "Dk_V2_Old_4" });

            var germanKeys_FromGateway = TestTemporaryExposureKeyBuilder.CreateDefault(_germany)
                                         .SetVisitedCountries(new[] { _poland })
                                         .SetKeySource(KeySource.Gateway)
                                         .Build(new[] { "De_Gate_1", "De_Gate_2", "De_Gate_3", "De_Gate_4", "De_Gate_5", "De_Gate_6" });

            var latviaKeys_FromGateway = TestTemporaryExposureKeyBuilder.CreateDefault(_latvia)
                                         .SetKeySource(KeySource.Gateway)
                                         .Build(new[] { "Lv_Gate_1", "Lv_Gate_2", "Lv_Gate_3", "Lv_Gate_4", "Lv_Gate_5", "Lv_Gate_6" });

            _dbContext.TemporaryExposureKey.AddRange(denmarkKeys_ApiV1);
            _dbContext.TemporaryExposureKey.AddRange(denmarkKeys_ApiV2);
            _dbContext.TemporaryExposureKey.AddRange(denmarkKeys_ApiV2_Old);
            _dbContext.TemporaryExposureKey.AddRange(germanKeys_FromGateway);
            _dbContext.TemporaryExposureKey.AddRange(latviaKeys_FromGateway);
            _dbContext.TemporaryExposureKey.AddRange(denmarkKeys_ApiV2_InvalidDaysSinceOnsetOfSymptoms);
            _dbContext.SaveChanges();

            // setup mock
            var gatewayHttpClientMock = new Mock <IGatewayHttpClient>();

            var expectedResponse = new HttpResponseMessage {
                StatusCode = HttpStatusCode.Created, Content = new StringContent("")
            };

            gatewayHttpClientMock.Setup(client => client.PostAsync(It.IsAny <string>(), It.IsAny <HttpContent>()))
            .ReturnsAsync(expectedResponse);

            var service = CreateGatewayServiceAndDependencies(gatewayHttpClientMock.Object);

            // .: Act
            service.UploadKeysToTheGateway(10, batchSize);

            // .: Verify
            var requestArgInterceptor = new ArgumentInterceptor <HttpContent>();

            gatewayHttpClientMock.Verify(c => c.PostAsync(It.IsAny <string>(), requestArgInterceptor.CreateCaptureAction()));

            var allBatchesPassedToHttpClient = ParseRequestBodiesBatches(requestArgInterceptor);
            var keysFromAllSentBatches       = allBatchesPassedToHttpClient.SelectMany(bath => bath.Keys).ToList();

            keysFromAllSentBatches.Should()
            .OnlyContain(key => key.Origin == _denmark.Code, because: "Only DK keys from APIV2 can be send to the UE Gateway.")
            .And.OnlyHaveUniqueItems(key => key.KeyData, because: "Service cannot send duplicates.")
            .And.OnlyContain(key => denmarkKeys_ApiV2.Any(keyApiv2 => EqualsKeyData(key.KeyData.ToByteArray(), keyApiv2.KeyData)));

            int expectedNumberOfBatches = (int)Math.Ceiling(denmarkKeys_ApiV2.Count / (decimal)batchSize);

            allBatchesPassedToHttpClient.Should()
            .NotBeNull()
            .And.HaveCount(expectedNumberOfBatches, because: "Keys needed to be send in batches");

            allBatchesPassedToHttpClient.ToList().ForEach(
                batch =>
            {
                batch.Keys.Should()
                .HaveCountGreaterThan(0, because: "Service cannot send empty requests.")
                .And.HaveCountLessOrEqualTo(batchSize, because: "Service cannot send batch with wrong size.")
                .And.OnlyHaveUniqueItems(key => key.KeyData, because: "Service cannot send duplicates.");
            });
        }
Ejemplo n.º 20
0
 public void RemoveKeys(List <TemporaryExposureKey> keys)
 {
     _dbContext.RemoveRange(keys);
     _dbContext.SaveChanges();
 }