public void GivenConsole_WhenMigrateCalledWithArguments_MigratesToNewVersion()
        {
            // Given
            string sourceFilePath  = ProjectMigrationTestHelper.GetOutdatedSupportedProjectFilePath();
            string targetFilePath  = TestHelper.GetScratchPadPath($"{nameof(RiskeerMigrationConsoleTest)}.{nameof(GivenConsole_WhenMigrateCalledWithArguments_MigratesToNewVersion)}");
            var    console         = new RiskeerMigrationConsole();
            string expectedVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            using (new FileDisposeHelper(targetFilePath))
            {
                using (var consoleOutput = new ConsoleOutput())
                {
                    // When
                    console.ExecuteConsoleTool(new[]
                    {
                        sourceFilePath,
                        targetFilePath
                    });

                    // Then
                    string expected = Environment.NewLine
                                      + $"Het projectbestand '{sourceFilePath}' is succesvol gemigreerd naar '{targetFilePath}' (versie {expectedVersion})."
                                      + Environment.NewLine;
                    string consoleText = consoleOutput.GetConsoleOutput();
                    Assert.AreEqual(expected, consoleText);

                    var toVersionedFile = new ProjectVersionedFile(targetFilePath);
                    Assert.AreEqual(expectedVersion, toVersionedFile.GetVersion());
                }
            }

            Assert.AreEqual(ErrorCode.ErrorSuccess, environmentControl.ErrorCodeCalled);
        }
Beispiel #2
0
        public void DetermineMigrationLocation_TargetFilePathIsEmpty_LogsMessageAndReturnsEmptyTargetPath()
        {
            // Setup
            const string originalFileName      = "Im_a_valid_file_path";
            const string expectedFileExtension = "risk";

            string validFilePath = TestHelper.GetScratchPadPath($"{originalFileName}.{expectedFileExtension}");

            var    expectedFileFilter        = new FileFilterGenerator(expectedFileExtension, "Riskeer project");
            string versionWithDashes         = ProjectVersionHelper.GetCurrentDatabaseVersion().Replace('.', '-');
            var    expectedSuggestedFileName = $"{originalFileName}_{versionWithDashes}";

            var mocks         = new MockRepository();
            var inquiryHelper = mocks.StrictMock <IInquiryHelper>();

            inquiryHelper.Expect(h => h.GetTargetFileLocation(expectedFileFilter.Filter, expectedSuggestedFileName))
            .Return(null);
            mocks.ReplayAll();

            var migrator       = new ProjectMigrator(inquiryHelper);
            var targetFilePath = "arbitraryPath";

            // Call
            void Call() => targetFilePath = migrator.DetermineMigrationLocation(validFilePath);

            // Assert
            var expectedLogMessage = Tuple.Create($"Het migreren van het projectbestand '{validFilePath}' is geannuleerd.",
                                                  LogLevelConstant.Warn);

            TestHelper.AssertLogMessageWithLevelIsGenerated(Call, expectedLogMessage, 1);

            Assert.IsNull(targetFilePath);
            mocks.VerifyAll();
        }
Beispiel #3
0
        public void LoadProject_DatabaseFromFutureVersion_ThrowStorageValidationException(int additionalVersionNumber)
        {
            // Setup
            string tempProjectFilePath    = Path.Combine(workingDirectory, $"{nameof(LoadProject_DatabaseFromFutureVersion_ThrowStorageValidationException)}_{Path.GetRandomFileName()}");
            string currentDatabaseVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            string versionCode            = additionalVersionNumber + currentDatabaseVersion;

            void Precondition()
            {
                SqLiteDatabaseHelper.CreateCompleteDatabaseFileEmpty(tempProjectFilePath);
                SqLiteDatabaseHelper.AddVersionEntity(tempProjectFilePath, versionCode);
            }

            Assert.DoesNotThrow(Precondition, "Precondition failed: creating future database file failed");

            // Call
            void Call() => new StorageSqLite().LoadProject(tempProjectFilePath);

            // Assert
            StorageException exception = Assert.Throws <StorageValidationException>(Call);

            Assert.IsInstanceOf <Exception>(exception);
            Assert.AreEqual($@"Fout bij het lezen van bestand '{tempProjectFilePath}': riskeer "
                            + $"bestand versie '{versionCode}' is hoger dan de huidig ondersteunde versie "
                            + $"('{currentDatabaseVersion}'). Update Riskeer naar een nieuwere versie.",
                            exception.Message);
        }
Beispiel #4
0
        public void DetermineMigrationLocation_ValidPath_AsksUserForTargetPathAndReturnsIt()
        {
            // Setup
            const string originalFileName      = "Im_a_valid_file_path";
            const string expectedFileExtension = "risk";

            string validFilePath = TestHelper.GetScratchPadPath($"{originalFileName}.{expectedFileExtension}");

            string versionWithDashes         = ProjectVersionHelper.GetCurrentDatabaseVersion().Replace('.', '-');
            var    expectedFileFilter        = new FileFilterGenerator(expectedFileExtension, "Riskeer project");
            string expectedSuggestedFileName = $"{originalFileName}_{versionWithDashes}";

            string expectedReturnPath = TestHelper.GetScratchPadPath("Im_a_file_path_to_the_migrated_file.risk");

            var mocks         = new MockRepository();
            var inquiryHelper = mocks.StrictMock <IInquiryHelper>();

            inquiryHelper.Expect(h => h.GetTargetFileLocation(expectedFileFilter.Filter, expectedSuggestedFileName))
            .Return(expectedReturnPath);
            mocks.ReplayAll();

            var migrator = new ProjectMigrator(inquiryHelper);

            // Call
            string targetFilePath = migrator.DetermineMigrationLocation(validFilePath);

            // Assert
            Assert.AreEqual(expectedReturnPath, targetFilePath);
            mocks.VerifyAll();
        }
Beispiel #5
0
        private static void ValidateDatabaseVersion(RiskeerEntities riskeerEntities, string databaseFilePath)
        {
            try
            {
                string databaseVersion = riskeerEntities.VersionEntities.Select(v => v.Version).Single();
                if (!ProjectVersionHelper.IsValidVersion(databaseVersion))
                {
                    string m = string.Format(Resources.StorageSqLite_ValidateDatabaseVersion_DatabaseVersion_0_is_invalid,
                                             databaseVersion);
                    string message = new FileReaderErrorMessageBuilder(databaseFilePath).Build(m);
                    throw new StorageValidationException(message);
                }

                if (ProjectVersionHelper.IsNewerThanCurrent(databaseVersion))
                {
                    string m = string.Format(Resources.StorageSqLite_ValidateDatabaseVersion_DatabaseVersion_0_higher_then_current_DatabaseVersion_1_,
                                             databaseVersion, ProjectVersionHelper.GetCurrentDatabaseVersion());
                    string message = new FileReaderErrorMessageBuilder(databaseFilePath).Build(m);
                    throw new StorageValidationException(message);
                }
            }
            catch (InvalidOperationException e)
            {
                string message = new FileReaderErrorMessageBuilder(databaseFilePath).Build(Resources.StorageSqLite_ValidateDatabaseVersion_Database_must_have_one_VersionEntity_row);
                throw new StorageValidationException(message, e);
            }
        }
        public void GivenConsole_WhenVersionSupportedCall_ThenReturnedIfSupported(string file, string fileVersion, bool isSupported)
        {
            // Given
            string sourceFilePath  = TestHelper.GetTestDataPath(TestDataPath.Riskeer.Migration.Core, file);
            var    console         = new RiskeerMigrationConsole();
            string expectedVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            using (var consoleOutput = new ConsoleOutput())
            {
                // When
                console.ExecuteConsoleTool(new[]
                {
                    sourceFilePath
                });

                // Then
                string consoleText  = consoleOutput.GetConsoleOutput();
                string expectedText = isSupported
                                          ? Environment.NewLine
                                      + $@"Het projectbestand kan gemigreerd worden naar versie '{expectedVersion}'."
                                      + Environment.NewLine
                                          : Environment.NewLine
                                      + $"Het migreren van een projectbestand met versie '{fileVersion}' naar versie '{expectedVersion}' is niet ondersteund."
                                      + Environment.NewLine;

                Assert.AreEqual(expectedText, consoleText);
                Assert.AreEqual(ErrorCode.ErrorSuccess, environmentControl.ErrorCodeCalled);
            }
        }
Beispiel #7
0
        public void LoadProject_DatabaseWithMultipleVersionEntities_ThrowStorageValidationException()
        {
            // Setup
            string projectFilePath        = Path.Combine(workingDirectory, nameof(LoadProject_DatabaseWithMultipleVersionEntities_ThrowStorageValidationException));
            string currentDatabaseVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            void Precondition()
            {
                SqLiteDatabaseHelper.CreateCompleteDatabaseFileEmpty(projectFilePath);
                SqLiteDatabaseHelper.AddVersionEntity(projectFilePath, currentDatabaseVersion);
                SqLiteDatabaseHelper.AddVersionEntity(projectFilePath, currentDatabaseVersion);
            }

            Assert.DoesNotThrow(Precondition, "Precondition failed: creating corrupt database file failed");

            // Call
            void Call() => new StorageSqLite().LoadProject(projectFilePath);

            // Assert
            StorageException exception = Assert.Throws <StorageValidationException>(Call);

            Assert.IsInstanceOf <Exception>(exception);
            Assert.AreEqual($@"Fout bij het lezen van bestand '{projectFilePath}': database moet één rij in de VersionEntity tabel hebben.",
                            exception.Message);
            Assert.IsInstanceOf <InvalidOperationException>(exception.InnerException);
        }
Beispiel #8
0
        /// <summary>
        /// Retrieves the file path of a project with the latest database version
        /// format that can be opened in the application.
        /// </summary>
        /// <returns>A file path to a project file with the latest database version.</returns>
        public static string GetLatestProjectFilePath()
        {
            string currentDatabaseVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            string versionSuffix          = currentDatabaseVersion.Replace(".", string.Empty);
            string projectFileName        = $"MigrationTestProject{versionSuffix}.risk";

            return(TestHelper.GetTestDataPath(testDataPath, projectFileName));
        }
Beispiel #9
0
        private static void MigrateFile(string sourceFilePath, string targetFilePath)
        {
            string newVersion        = ProjectVersionHelper.GetCurrentDatabaseVersion();
            var    fromVersionedFile = new ProjectVersionedFile(sourceFilePath);
            var    migrator          = new ProjectFileMigrator();

            migrator.Migrate(fromVersionedFile, newVersion, targetFilePath);
        }
Beispiel #10
0
        public void GetCurrentDatabaseVersion_ReturnsExpectedValue()
        {
            // Call
            string currentVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            // Assert
            Assert.AreEqual("22.2", currentVersion);
        }
Beispiel #11
0
        public void IsNewerThanCurrentString_InvalidVersion_ReturnsFalse(string invalidVersion)
        {
            // Call
            bool isNewer = ProjectVersionHelper.IsNewerThanCurrent(invalidVersion);

            // Assert
            Assert.IsFalse(isNewer);
        }
Beispiel #12
0
        public void IsNewerThanCurrentString_NewerVersion_ReturnsTrue(string newerVersion)
        {
            // Call
            bool isNewer = ProjectVersionHelper.IsNewerThanCurrent(newerVersion);

            // Assert
            Assert.IsTrue(isNewer);
        }
Beispiel #13
0
        public void IsValidVersion_ValidVersion_ReturnsTrue(string validVersion)
        {
            // Call
            bool isNewer = ProjectVersionHelper.IsValidVersion(validVersion);

            // Assert
            Assert.IsTrue(isNewer);
        }
Beispiel #14
0
        public void ValidateVersion_ValidVersion_DoesNotThrowException(string validVersion)
        {
            // Call
            void Call() => ProjectVersionHelper.ValidateVersion(validVersion);

            // Assert
            Assert.DoesNotThrow(Call);
        }
Beispiel #15
0
        public void ValidateVersion_InvalidVersion_ThrowArgumentException(string validVersion)
        {
            // Call
            void Call() => ProjectVersionHelper.ValidateVersion(validVersion);

            // Assert
            var expectedMessage = $@"'{validVersion}' is geen geldige Riskeer of Ringtoets projectbestand versie.";

            TestHelper.AssertThrowsArgumentExceptionAndTestMessage <ArgumentException>(Call, expectedMessage);
        }
Beispiel #16
0
        public void IsNewerThanCurrentString_SameVersion_ReturnsFalse()
        {
            // Setup
            string currentVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            // Call
            bool isNewer = ProjectVersionHelper.IsNewerThanCurrent(currentVersion);

            // Assert
            Assert.IsFalse(isNewer);
        }
Beispiel #17
0
        /// <summary>
        /// Creates a new instance of the <see cref="ProjectCreateScript"/> class.
        /// </summary>
        /// <param name="version">The version <paramref name="query"/> was designed for.</param>
        /// <param name="query">The SQL query that belongs to <paramref name="version"/>.</param>
        /// <exception cref="ArgumentException">Thrown when:
        /// <list type="bullet">
        /// <item><paramref name="version"/> is not a valid project version,</item>
        /// <item><paramref name="query"/> is empty, <c>null</c>, or consist out of only whitespace characters.</item>
        /// </list></exception>
        public ProjectCreateScript(string version, string query) : base(version)
        {
            ProjectVersionHelper.ValidateVersion(version);

            if (string.IsNullOrWhiteSpace(query))
            {
                throw new ArgumentException(@"Query must have a value.", nameof(query));
            }

            createQuery = query;
        }
Beispiel #18
0
        public void Constructor_ValidParameters_ExpectedValues()
        {
            // Setup
            const string query   = "Valid query";
            string       version = ProjectVersionHelper.GetCurrentDatabaseVersion();

            // Call
            var createScript = new ProjectCreateScript(version, query);

            // Assert
            Assert.IsInstanceOf <CreateScript>(createScript);
            Assert.AreEqual(version, createScript.GetVersion());
        }
Beispiel #19
0
        public void Constructor_InvalidQuery_ThrowsArgumentException(string query)
        {
            // Setup
            string version = ProjectVersionHelper.GetCurrentDatabaseVersion();

            // Call
            TestDelegate call = () => new ProjectCreateScript(version, query);

            // Assert
            string paramName = Assert.Throws <ArgumentException>(call).ParamName;

            Assert.AreEqual("query", paramName);
        }
        public void Constructor_ToVersionNullOrEmpty_ThrowsArgumentException(string toVersion)
        {
            // Setup
            string       fromVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            const string query       = "Valid query";

            // Call
            TestDelegate call = () => new ProjectUpgradeScript(fromVersion, toVersion, query, string.Empty);

            // Assert
            string paramName = Assert.Throws <ArgumentException>(call).ParamName;

            Assert.AreEqual("toVersion", paramName);
        }
        public void Constructor_InvalidToVersion_ThrowsArgumentException(string toVersion)
        {
            // Setup
            string       fromVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            const string query       = "Valid query";

            // Call
            TestDelegate call = () => new ProjectUpgradeScript(fromVersion, toVersion, query, string.Empty);

            // Assert
            string expectedMessage = $@"'{toVersion}' is geen geldige Riskeer of Ringtoets projectbestand versie.";

            TestHelper.AssertThrowsArgumentExceptionAndTestMessage <ArgumentException>(call, expectedMessage);
        }
        /// <summary>
        /// Creates a new instance of the <see cref="ProjectUpgradeScript"/> class.
        /// </summary>
        /// <param name="fromVersion">The source version <paramref name="query"/> was designed for.</param>
        /// <param name="toVersion">The target version <paramref name="query"/> was designed for.</param>
        /// <param name="query">The SQL query to upgrade from <paramref name="fromVersion"/> to <paramref name="toVersion"/>.</param>
        /// <param name="logDatabaseLocation">The location to the log database.</param>
        /// <exception cref="ArgumentException">Thrown when:
        /// <list type="bullet">
        /// <item><paramref name="fromVersion"/> is not a valid project version,</item>
        /// <item><paramref name="toVersion"/> is not a valid project version,</item>
        /// <item><paramref name="query"/> is empty, <c>null</c>, or consists out of only whitespace characters.</item>
        /// </list></exception>
        public ProjectUpgradeScript(string fromVersion, string toVersion, string query, string logDatabaseLocation)
            : base(fromVersion, toVersion)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                throw new ArgumentException(@"Query must have a value.", nameof(query));
            }

            ProjectVersionHelper.ValidateVersion(fromVersion);
            ProjectVersionHelper.ValidateVersion(toVersion);

            upgradeQuery             = query;
            this.logDatabaseLocation = logDatabaseLocation;
        }
        public void Constructor_ValidParameters_ReturnsExpectedValues()
        {
            // Setup
            string       fromVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            string       toVersion   = ProjectVersionHelper.GetCurrentDatabaseVersion();
            const string query       = ";";

            // Call
            var upgradeScript = new ProjectUpgradeScript(fromVersion, toVersion, query, string.Empty);

            // Assert
            Assert.IsInstanceOf <UpgradeScript>(upgradeScript);
            Assert.AreEqual(fromVersion, upgradeScript.FromVersion());
            Assert.AreEqual(toVersion, upgradeScript.ToVersion());
        }
Beispiel #24
0
        public void CreateEmptyVersionedFile_FileDoesNotExist_ReturnsVersionedFile()
        {
            // Setup
            const string query   = ";";
            string       version = ProjectVersionHelper.GetCurrentDatabaseVersion();

            string filePath     = TestHelper.GetScratchPadPath(nameof(CreateEmptyVersionedFile_FileDoesNotExist_ReturnsVersionedFile));
            var    createScript = new ProjectCreateScript(version, query);

            // Call
            IVersionedFile versionedFile = createScript.CreateEmptyVersionedFile(filePath);

            // Assert
            Assert.IsTrue(File.Exists(versionedFile.Location));
            File.Delete(filePath);
        }
        public void Upgrade_ValidParameters_ExpectedProperties()
        {
            // Setup
            string filePath    = TestHelper.GetScratchPadPath(nameof(Upgrade_ValidParameters_ExpectedProperties));
            string fromVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            string toVersion   = ProjectVersionHelper.GetCurrentDatabaseVersion();

            var upgradeScript = new ProjectUpgradeScript(fromVersion, toVersion, ";", "");

            // Call
            upgradeScript.Upgrade("c:\\file.ext", filePath);

            // Assert
            Assert.IsTrue(File.Exists(filePath));
            File.Delete(filePath);
        }
Beispiel #26
0
        public void CreateEmptyVersionedFile_QueryFails_ThrowsCriticalMigrationException()
        {
            // Setup
            const string query   = "THIS WILL FAIL";
            string       version = ProjectVersionHelper.GetCurrentDatabaseVersion();

            string filePath     = TestHelper.GetScratchPadPath(nameof(CreateEmptyVersionedFile_QueryFails_ThrowsCriticalMigrationException));
            var    createScript = new ProjectCreateScript(version, query);

            // Call
            TestDelegate call = () => createScript.CreateEmptyVersionedFile(filePath);

            // Assert
            using (new FileDisposeHelper(filePath))
            {
                var exception = Assert.Throws <CriticalMigrationException>(call);
                Assert.AreEqual($"Het aanmaken van het Riskeer projectbestand met versie '{version}' is mislukt.",
                                exception.Message);
                Assert.IsInstanceOf <SQLiteException>(exception.InnerException);
            }
        }
        private static string GetConsoleFullDescription()
        {
            string currentDatabaseVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();

            return("Dit hulpprogramma kan worden gebruikt om een projectbestand in het formaat van een "
                   + $"eerdere versie van Riskeer of Ringtoets projectbestand te migreren naar het formaat van de huidige versie van Riskeer ({currentDatabaseVersion})."
                   + Environment.NewLine + Environment.NewLine
                   + "MIGRATIEHULPPROGRAMMA -h" + Environment.NewLine
                   + "MIGRATIEHULPPROGRAMMA --help" + Environment.NewLine
                   + "          Geeft deze informatie weer." + Environment.NewLine + Environment.NewLine
                   + "MIGRATIEHULPPROGRAMMA bronprojectpad" + Environment.NewLine
                   + "          Controleert of het projectbestand dat te vinden is in het bronproject"
                   + Environment.NewLine
                   + "          pad gemigreerd kan worden." + Environment.NewLine + Environment.NewLine
                   + "MIGRATIEHULPPROGRAMMA bronprojectpad doelprojectpad" + Environment.NewLine
                   + "          Voert de migratie uit van het projectbestand dat te vinden is in het "
                   + Environment.NewLine
                   + "          bronprojectpad en slaat het resulterende projectbestand op in het doe"
                   + Environment.NewLine
                   + "          lprojectpad." + Environment.NewLine + Environment.NewLine);
        }
        public void Upgrade_UpgradeFails_ThrowsCriticalMigrationException()
        {
            // Setup
            string fromVersion = ProjectVersionHelper.GetCurrentDatabaseVersion();
            string toVersion   = ProjectVersionHelper.GetCurrentDatabaseVersion();

            string fileLocation  = TestHelper.GetScratchPadPath(nameof(Upgrade_UpgradeFails_ThrowsCriticalMigrationException));
            var    upgradeScript = new ProjectUpgradeScript(fromVersion, toVersion, "THIS WILL FAIL", string.Empty);

            using (new FileDisposeHelper(fileLocation))
            {
                // Call
                TestDelegate call = () => upgradeScript.Upgrade(fileLocation, fileLocation);

                // Assert
                var exception = Assert.Throws <CriticalMigrationException>(call);
                Assert.AreEqual($"Het migreren van het Riskeer of Ringtoets projectbestand van versie '{fromVersion}' naar '{fromVersion}' is mislukt.",
                                exception.Message);
                Assert.IsInstanceOf <SQLiteException>(exception.InnerException);
            }
        }
Beispiel #29
0
        private void SaveProjectInDatabase(string databaseFilePath)
        {
            string connectionString = GetConnectionToNewFile(databaseFilePath);

            using (var dbContext = new RiskeerEntities(connectionString))
            {
                try
                {
                    dbContext.VersionEntities.Add(new VersionEntity
                    {
                        Version     = ProjectVersionHelper.GetCurrentDatabaseVersion(),
                        Timestamp   = DateTime.Now,
                        FingerPrint = FingerprintHelper.Get(stagedProject.Entity)
                    });
                    dbContext.ProjectEntities.Add(stagedProject.Entity);
                    dbContext.SaveChanges();
                }
                catch (DataException exception)
                {
                    throw CreateStorageWriterException(databaseFilePath, Resources.Error_saving_database, exception);
                }
                catch (CannotDetermineFingerprintException exception)
                {
                    throw CreateStorageWriterException(databaseFilePath, exception.Message, exception);
                }
                catch (SystemException exception)
                {
                    if (exception is InvalidOperationException || exception is NotSupportedException)
                    {
                        throw CreateStorageWriterException(databaseFilePath, Resources.Error_during_connection, exception);
                    }

                    throw;
                }

                stagedProject.Model.Name = Path.GetFileNameWithoutExtension(databaseFilePath);
            }
        }
Beispiel #30
0
        public void CreateEmptyVersionedFile_FileExistsButNotWritable_ThrowsArgumentException()
        {
            // Setup
            const string query   = ";";
            string       version = ProjectVersionHelper.GetCurrentDatabaseVersion();

            string filePath     = TestHelper.GetScratchPadPath(nameof(CreateEmptyVersionedFile_FileExistsButNotWritable_ThrowsArgumentException));
            var    createScript = new ProjectCreateScript(version, query);

            using (new FileDisposeHelper(filePath))
            {
                FileAttributes attributes = File.GetAttributes(filePath);
                File.SetAttributes(filePath, attributes | FileAttributes.ReadOnly);

                // Call
                TestDelegate call = () => createScript.CreateEmptyVersionedFile(filePath);

                // Assert
                var exception = Assert.Throws <ArgumentException>(call);
                Assert.AreEqual("path", exception.ParamName);
                File.SetAttributes(filePath, attributes);
            }
        }