Esempio n. 1
0
        public async void LogMessage_CreateModelsStoreInDatabasePullFromDatabaseConvertToDtos_DtosShouldContainCorrectValues()
        {
            DependencyInjectionConfig.Init();

            // Clear the mock database
            ILoggingManager logManager = ServiceLocator.Current.GetInstance <ILoggingManager>();
            await logManager.DeleteAll();

            // Log models to the mock database
            LogUtils.LogMessage(Enums.LogSeverity.INFO, "My message");
            LogUtils.LogMessage(Enums.LogSeverity.WARNING, "My message", "Additional info");
            LogUtils.LogMessage(Enums.LogSeverity.ERROR, "");

            //// Wait for async IO operations
            //await Task.Delay(1000);

            // Pull models from the mock database
            List <LogSQLiteModel> logSqliteModels = await logManager.GetLogs(10);

            Assert.Equal(3, logSqliteModels.Count);

            // Convert models to DTOs
            IEnumerable <LogDTO> logDtos = logSqliteModels.Select(x => new LogDTO(x));

            //Check that DTOs correspond with arguments to LogMessage()
            foreach (LogDTO logDto in logDtos)
            {
                if (logDto.Severity == Enums.LogSeverity.INFO.ToString())
                {
                    Assert.Equal("My message", logDto.Description);
                }
                else if (logDto.Severity == Enums.LogSeverity.WARNING.ToString())
                {
                    Assert.Equal("My message", logDto.Description);
                    Assert.Equal("Additional info (GPS: Mock version)", logDto.AdditionalInfo);
                }
                else if (logDto.Severity == Enums.LogSeverity.ERROR.ToString())
                {
                    Assert.Equal("", logDto.Description);
                }
                else
                {
                    throw new Exception("At least one of the ifs is expected to be true");
                }
            }
        }
Esempio n. 2
0
        public PullKeysTests()
        {
            DependencyInjectionConfig.Init();
            string zipDirectory = ServiceLocator.Current.GetInstance <IFileSystem>().CacheDirectory;

            if (!Directory.Exists(zipDirectory))
            {
                Directory.CreateDirectory(zipDirectory);
            }
            _helper = new ZipDownloaderHelper();

            _preferences    = ServiceLocator.Current.GetInstance <IPreferences>();
            _logManager     = ServiceLocator.Current.GetInstance <ILoggingManager>();
            _developerTools = ServiceLocator.Current.GetInstance <IDeveloperToolsService>();
            _preferences.Clear();
            _logManager.DeleteAll();
            _developerTools.ClearAllFields();
        }
        public static async void SendAllLogs()
        {
            UpdateCorrelationId(null);
            ILoggingManager manager = ServiceLocator.Current.GetInstance <ILoggingManager>();

            try
            {
                bool allLogsSent = false;
                while (!allLogsSent)
                {
                    List <LogSQLiteModel> logs = await manager.GetLogs(_numLogsToSendAtATime);

                    if (logs == null || !logs.Any())
                    {
                        break;
                    }

                    // Try to post logs to the server
                    List <LogDTO> dto     = logs.Select(l => new LogDTO(l)).ToList();
                    bool          success = await(new LoggingService()).PostAllLogs(dto);

                    // If posting succeeded, delete them
                    if (success)
                    {
                        await manager.DeleteLogs(logs);
                    }
                    // Else, we must try to send them another time.
                    // Also make sure we don't store too many logs because sending keeps failing
                    else
                    {
                        DeleteLogsIfTooMany();
                        break;
                    }

                    allLogsSent = logs.Count < _numLogsToSendAtATime;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Print($"{nameof(LogUtils)}.{nameof(SendAllLogs)}: Failed to send logs. Wiping DB to prevent deadlock");
                System.Diagnostics.Debug.Print(e.ToString());
                await manager.DeleteAll();
            }
        }
        public async void createAValidListOfTemporaryExposureKeys_GeneratesProperLogIfKeysAreFiltered(int ExtraKeys)
        {
            SystemTime.ResetDateTime();
            await _logManager.DeleteAll();

            // Create a list of 15 keys
            IEnumerable <ExposureKeyModel> temporaryExposureKeys = new List <ExposureKeyModel>();

            for (int i = 0; i < 14 + ExtraKeys; i++)
            {
                temporaryExposureKeys = temporaryExposureKeys.Append(new ExposureKeyModel(new byte[i + 1], SystemTime.Now().AddDays(0 - i), TimeSpan.FromDays(1), RiskLevel.Medium));
            }

            // Process them
            IEnumerable <ExposureKeyModel> processedKeys = UploadDiagnosisKeysHelper.CreateAValidListOfTemporaryExposureKeys(temporaryExposureKeys);

            // Check if log is generated
            string logStatement = _logManager.GetLogs(1).Result.ElementAt(0).Description;

            Assert.Equal(ExtraKeys.ToString(), logStatement.Last().ToString());
        }
Esempio n. 5
0
        public async void LogException_CreateModelsStoreInDatabasePullFromDatabaseConvertToDtos_DtosShouldContainCorrectValues()
        {
            // Clear the mock database
            ILoggingManager logManager = ServiceLocator.Current.GetInstance <ILoggingManager>();
            await logManager.DeleteAll();

            // Log models to the mock database
            LogUtils.LogException(Enums.LogSeverity.INFO, new Exception("Hello"),
                                  "My context description");
            LogUtils.LogException(Enums.LogSeverity.WARNING, new Exception("Goodbye"),
                                  "Context decription", "Additional info");

            // Pull models from the mock database
            List <LogSQLiteModel> logSqliteModels = await logManager.GetLogs(10);

            Assert.Equal(2, logSqliteModels.Count);


            // Convert models to DTOs
            IEnumerable <LogDTO> logDtos = logSqliteModels.Select(x => new LogDTO(x));

            // Check that DTOs correspond with arguments to LogMessage()
            foreach (LogDTO logDto in logDtos)
            {
                if (logDto.Severity == Enums.LogSeverity.INFO.ToString())
                {
                    Assert.Equal("Hello", logDto.ExceptionMessage);
                }
                else if (logDto.Severity == Enums.LogSeverity.WARNING.ToString())
                {
                    // (GPS: Mock version) is added in the Logdetails constructor
                    Assert.Equal("Additional info (GPS: Mock version)", logDto.AdditionalInfo);
                }
                else
                {
                    throw new Exception("At least one of the ifs is expected to be true");
                }
            }
        }
Esempio n. 6
0
        public async void PullKeys_MissingOrBadHeader()
        {
            //Given that the MoreBatchesExist header is missing (batch 3)
            ExposureNotificationWebService mockedService = _helper.MockedService(new List <PullKeysMockData>
            {
                new PullKeysMockData(day1, 1).HttpStatusCode(200).WithLastBatchHeader(1).WithMoreBatchesExistHeader(true),
                new PullKeysMockData(day1, 2).HttpStatusCode(200).WithLastBatchHeader(2).WithMoreBatchesExistHeader(true),
                new PullKeysMockData(day1, 3).HttpStatusCode(200).WithLastBatchHeader(3),
                new PullKeysMockData(day1, 4).HttpStatusCode(204),
            });

            //Given today is day1
            SystemTime.SetDateTime(day1);

            //Given last time we pulled was day, batch3.
            _helper.SetLastPulledDate(day1, 1);

            //When pulling keys
            List <string> zipLocations = (await new ZipDownloader().PullNewKeys(mockedService, new CancellationToken())).ToList();

            //Then the missing header is considered a failed pull, only batch 2 was successfull
            Assert.Single(zipLocations);
            Assert.Equal(2, LocalPreferencesHelper.LastPullKeysBatchNumberNotSubmitted); //The last batch number is saved from header

            //An error was logged
            List <LogSQLiteModel> logs = await _logManager.GetLogs(10);

            Assert.Single(logs);
            string expectedErrorMessage = $"Failed to parse {ZipDownloader.MoreBatchesExistHeader} or {ZipDownloader.LastBatchReturnedHeader} header.";

            Assert.Contains(expectedErrorMessage, logs[0].Description);
            Assert.Equal(LogSeverity.ERROR.ToString(), logs[0].Severity);
            Assert.Contains(expectedErrorMessage, _developerTools.LastPullHistory);

            //Prepare for new pull
            LocalPreferencesHelper.UpdateLastPullKeysSucceededDateTime();
            await _logManager.DeleteAll();

            _developerTools.ClearAllFields();

            //If LastBatchHeader is missing
            ExposureNotificationWebService mockedService2 = _helper.MockedService(new List <PullKeysMockData>
            {
                new PullKeysMockData(day1, 1).HttpStatusCode(200).WithLastBatchHeader(1).WithMoreBatchesExistHeader(true),
                new PullKeysMockData(day1, 2).HttpStatusCode(200).WithLastBatchHeader(2).WithMoreBatchesExistHeader(true),
                new PullKeysMockData(day1, 3).HttpStatusCode(200).WithMoreBatchesExistHeader(false),
                new PullKeysMockData(day1, 4).HttpStatusCode(204),
            });

            //When pulling keys
            List <string> zipLocations2 = (await new ZipDownloader().PullNewKeys(mockedService2, new CancellationToken())).ToList();

            //Then the missing header is considered a failed pull, there were no successfull new pulls
            Assert.Empty(zipLocations2);
            Assert.Equal(2, LocalPreferencesHelper.LastPullKeysBatchNumberNotSubmitted); //The last batch number is not updated

            //An error was logged
            logs = await _logManager.GetLogs(10);

            Assert.Single(logs);
            Assert.Contains(expectedErrorMessage, logs[0].Description);
            Assert.Equal(LogSeverity.ERROR.ToString(), logs[0].Severity);
            Assert.Contains(expectedErrorMessage, _developerTools.LastPullHistory);
        }
 public UploadDIagnosisKeysHelperTests()
 {
     DependencyInjectionConfig.Init();
     _logManager = ServiceLocator.Current.GetInstance <ILoggingManager>();
     _logManager.DeleteAll();
 }
Esempio n. 8
0
        public async void LogApiError_CreateModelsStoreInDatabasePullFromDatabaseConvertToDtos_DtosShouldContainCorrectValues()
        {
            // Clear the mock database
            ILoggingManager logManager = ServiceLocator.Current.GetInstance <ILoggingManager>();
            await logManager.DeleteAll();

            // Log apiResponse1

            string urlPrefix = Conf.URL_PREFIX;

            ApiResponse apiResponse1 = new ApiResponse(urlPrefix + "HELLO!", HttpMethod.Get);

            apiResponse1.StatusCode = 200;
            IEnumerable <ExposureKeyModel> temporaryExposureKeys = new List <ExposureKeyModel>()
            {
                new ExposureKeyModel(new byte[5], DateTimeOffset.FromUnixTimeSeconds(1234), TimeSpan.FromHours(24), RiskLevel.Medium),
                new ExposureKeyModel(new byte[5], DateTimeOffset.FromUnixTimeSeconds(1234), TimeSpan.FromHours(24), RiskLevel.Medium),
                new ExposureKeyModel(new byte[5], DateTimeOffset.FromUnixTimeSeconds(1234), TimeSpan.FromHours(24), RiskLevel.Medium),
            };

            string redactedKeysJson = RedactedTekListHelper.CreateRedactedTekList(temporaryExposureKeys);

            LogUtils.LogApiError(Enums.LogSeverity.INFO, apiResponse1,
                                 false, redactedKeysJson);

            //Added Mockversion to test if version is set correctly in the Logdevicedetails
            redactedKeysJson += " (GPS: Mock version)";

            // Log apiResponse2

            ApiResponse apiResponse2 = new ApiResponse(urlPrefix + "GOODBYE!", HttpMethod.Get);

            apiResponse2.StatusCode = 201;
            LogUtils.LogApiError(Enums.LogSeverity.WARNING, apiResponse2, true);

            // Pull the two log models from the mock database
            List <LogSQLiteModel> logSqliteModels = await logManager.GetLogs(10);

            Assert.Equal(2, logSqliteModels.Count);

            // Convert the models to DTOs
            IEnumerable <LogDTO> logDtos = logSqliteModels.Select(x => new LogDTO(x));

            // Check that the DTOs contain the expected values
            foreach (LogDTO logDto in logDtos)
            {
                // apiReponse1
                string apiVersion = $"/v{Conf.APIVersion}/";

                if (logDto.Severity == Enums.LogSeverity.INFO.ToString())
                {
                    Assert.Equal(apiVersion + "HELLO!", logDto.Api);
                    Assert.Equal(200, logDto.ApiErrorCode);

                    // We expect AdditionalInfo to consist of redactedKeysJson, after it's been processed with RedactText
                    Assert.Equal(RedactText(redactedKeysJson), logDto.AdditionalInfo);

                    // This part is just to double check redaction of key data works
                    // Before redaction, the key data is a byte array of size 5, which is shown as "AAAAAAA="
                    // After redaction we do not want this to be in the string
                    string nonRedactedKeysJson = JsonConvert.SerializeObject(temporaryExposureKeys, BaseWebService.JsonSerializerSettings);
                    Assert.Contains("AAAAAAA=", nonRedactedKeysJson);
                    Assert.DoesNotContain("AAAAAAA=", redactedKeysJson);
                }

                // apiResponse2

                else if (logDto.Severity == Enums.LogSeverity.WARNING.ToString())
                {
                    Assert.Equal(apiVersion + "GOODBYE!", logDto.Api);
                    Assert.Equal(201, logDto.ApiErrorCode);
                }

                // Should never be reached
                else
                {
                    throw new Exception("At least one of the ifs is expected to be true");
                }
            }
        }