Exemple #1
0
        public void SaveProjectAs_ValidPathToLockedFile_ThrowsUpdateStorageException()
        {
            // Setup
            string         tempProjectFilePath = Path.Combine(workingDirectory, nameof(SaveProjectAs_ValidPathToLockedFile_ThrowsUpdateStorageException));
            RiskeerProject project             = CreateProject();
            var            storage             = new StorageSqLite();

            storage.StageProject(project);

            using (var fileDisposeHelper = new FileDisposeHelper(tempProjectFilePath))
            {
                try
                {
                    fileDisposeHelper.LockFiles();

                    // Call
                    void Call() => storage.SaveProjectAs(tempProjectFilePath);

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

                    Assert.IsInstanceOf <Exception>(exception);
                    Assert.IsInstanceOf <IOException>(exception.InnerException);
                    Assert.IsInstanceOf <Exception>(exception);
                    Assert.AreEqual("Het doelbestand is momenteel in gebruik.", exception.Message);
                }
                finally
                {
                    CallGarbageCollector();
                }
            }
        }
        public void Perform_TemporaryFileInUse_ExpectedExceptionThrown(bool performWithExistingTargetFile)
        {
            // Setup
            string writableDirectory = Path.Combine(testWorkDir, nameof(Perform_TemporaryFileInUse_ExpectedExceptionThrown));
            string targetFilePath    = Path.Combine(writableDirectory, "targetFile.txt");
            string temporaryFilePath = Path.ChangeExtension(targetFilePath, temporaryFileExtension);

            using (new DirectoryDisposeHelper(testWorkDir, nameof(Perform_TemporaryFileInUse_ExpectedExceptionThrown)))
                using (var fileDisposeHelper = new FileDisposeHelper(temporaryFilePath))
                {
                    fileDisposeHelper.LockFiles();

                    if (performWithExistingTargetFile)
                    {
                        File.WriteAllText(targetFilePath, testContent);
                    }

                    var writer = new SafeFileWriter(targetFilePath, temporaryFileExtension);

                    // Call
                    var exception = Assert.Throws <IOException>(() => writer.Perform(() => {}));

                    // Assert
                    Assert.AreEqual("Het doelbestand is momenteel in gebruik.", exception.Message);
                }
        }
        public void GivenConsole_WhenMigrateCalledUnableToSaveTarget_ThenExitWithErrorCode()
        {
            // Given
            string sourceFilePath = ProjectMigrationTestHelper.GetOutdatedSupportedProjectFilePath();
            string targetFilePath = TestHelper.GetScratchPadPath($"{nameof(RiskeerMigrationConsoleTest)}.{nameof(GivenConsole_WhenMigrateCalledUnableToSaveTarget_ThenExitWithErrorCode)}");

            var console = new RiskeerMigrationConsole();

            using (var fileDisposeHelper = new FileDisposeHelper(targetFilePath))
                using (var consoleOutput = new ConsoleOutput())
                {
                    fileDisposeHelper.LockFiles();

                    // When
                    console.ExecuteConsoleTool(new[]
                    {
                        sourceFilePath,
                        targetFilePath
                    });

                    // Then
                    string consoleText = consoleOutput.GetConsoleOutput();
                    StringAssert.StartsWith(Environment.NewLine + "Het gemigreerde projectbestand is aangemaakt op '",
                                            consoleText);
                    StringAssert.EndsWith($"', maar er is een onverwachte fout opgetreden tijdens het verplaatsen naar '{targetFilePath}'."
                                          + Environment.NewLine
                                          + "Het besturingssysteem geeft de volgende melding: "
                                          + Environment.NewLine
                                          + $"The process cannot access the file '{targetFilePath}' because it is being used by another process."
                                          + Environment.NewLine + Environment.NewLine
                                          + GetConsoleFullDescription(), consoleText);
                    Assert.AreEqual(ErrorCode.ErrorBadCommand, environmentControl.ErrorCodeCalled);
                }
        }
        public void Export_InvalidDirectoryRights_LogsErrorAndReturnsFalse()
        {
            // Setup
            string            filePath          = TestHelper.GetScratchPadPath(nameof(Export_InvalidDirectoryRights_LogsErrorAndReturnsFalse));
            AssessmentSection assessmentSection = CreateConfiguredAssessmentSection();

            var exporter = new AssemblyExporter(assessmentSection, filePath);

            using (var fileDisposeHelper = new FileDisposeHelper(filePath))
                using (new AssemblyToolCalculatorFactoryConfig())
                {
                    var calculatorFactory = (TestAssemblyToolCalculatorFactory)AssemblyToolCalculatorFactory.Instance;
                    AssessmentSectionAssemblyCalculatorStub assessmentSectionAssemblyCalculator = calculatorFactory.LastCreatedAssessmentSectionAssemblyCalculator;
                    assessmentSectionAssemblyCalculator.CombinedFailureMechanismSectionAssemblyOutput = new CombinedFailureMechanismSectionAssemblyResultWrapper(
                        Array.Empty <CombinedFailureMechanismSectionAssembly>(), AssemblyMethod.BOI3A1, AssemblyMethod.BOI3B1, AssemblyMethod.BOI3C1);

                    fileDisposeHelper.LockFiles();

                    // Call
                    var isExported            = true;
                    void Call() => isExported = exporter.Export();

                    // Assert
                    string expectedMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'. " +
                                             "Er zijn geen assemblageresultaten geëxporteerd.";
                    TestHelper.AssertLogMessageWithLevelIsGenerated(Call, new Tuple <string, LogLevelConstant>(expectedMessage, LogLevelConstant.Error));
                    Assert.IsFalse(isExported);
                }
        }
Exemple #5
0
        public void Migrate_TargetFileInUse_ThrowsCriticalDatabaseMigrationException()
        {
            // Setup
            const string newVersion        = "17.1";
            string       sourceFilePath    = ProjectMigrationTestHelper.GetOutdatedSupportedProjectFilePath();
            var          fromVersionedFile = new ProjectVersionedFile(sourceFilePath);

            string targetFilePath = TestHelper.GetScratchPadPath(nameof(Migrate_TargetFileInUse_ThrowsCriticalDatabaseMigrationException));
            var    migrator       = new ProjectFileMigrator();

            using (var fileDisposeHelper = new FileDisposeHelper(targetFilePath))
            {
                fileDisposeHelper.LockFiles();

                // Call
                TestDelegate call = () => migrator.Migrate(fromVersionedFile, newVersion, targetFilePath);

                // Assert
                var exception = Assert.Throws <CriticalMigrationException>(call);
                StringAssert.StartsWith("Het gemigreerde projectbestand is aangemaakt op '", exception.Message);
                StringAssert.EndsWith($"', maar er is een onverwachte fout opgetreden tijdens het verplaatsen naar '{targetFilePath}'.",
                                      exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
Exemple #6
0
        public void GivenWmtsLocationControl_WhenAddLocationClickedAndConfigFileInUse_ThenWmtsLocationsNotUpdatedAndLogGenerated()
        {
            // Given
            mockRepository.ReplayAll();

            const string name = @"someName";
            const string url = @"someUrl";
            const string noConfigFolderName = "noConfig";

            DialogBoxHandler = (formName, wnd) =>
            {
                using (var formTester = new FormTester(formName))
                {
                    var dialog = (WmtsConnectionDialog) formTester.TheObject;
                    TextBox nameTextBox = dialog.Controls.Find("nameTextBox", true).OfType<TextBox>().First();
                    TextBox urlTextBox = dialog.Controls.Find("urlTextBox", true).OfType<TextBox>().First();
                    var actionButton = new ButtonTester("actionButton", dialog);

                    nameTextBox.Text = name;
                    urlTextBox.Text = url;

                    actionButton.Click();
                }
            };

            using (new UseCustomSettingsHelper(new TestSettingsHelper
            {
                ApplicationLocalUserSettingsDirectory = Path.Combine(TestHelper.GetScratchPadPath(), noConfigFolderName)
            }))
            using (new DirectoryDisposeHelper(TestHelper.GetScratchPadPath(), noConfigFolderName))
            {
                string configFilePath = Path.Combine(SettingsHelper.Instance.GetApplicationLocalUserSettingsDirectory(),
                                                     wmtsconnectioninfoConfigFile);

                using (var fileDisposeHelper = new FileDisposeHelper(configFilePath))
                using (new UseCustomTileSourceFactoryConfig(tileFactory))
                using (var form = new Form())
                using (var control = new WmtsLocationControl(null, wmtsCapabilityFactory))
                {
                    form.Controls.Add(control);
                    form.Show();

                    fileDisposeHelper.LockFiles();

                    var buttonAddLocation = new ButtonTester("addLocationButton", form);

                    // When
                    Action action = () => buttonAddLocation.Click();

                    // Then
                    string exceptionMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{configFilePath}'.";
                    TestHelper.AssertLogMessageWithLevelIsGenerated(action, Tuple.Create(exceptionMessage, LogLevelConstant.Error));
                    ComboBox urlLocations = form.Controls.Find("urlLocationComboBox", true).OfType<ComboBox>().First();
                    var dataSource = (IList<WmtsConnectionInfo>) urlLocations.DataSource;
                    Assert.AreEqual(1, dataSource.Count);
                }
            }
        }
        public void CreateDatabaseStructure_ValidExistingFile_ThrowsStorageException()
        {
            string tempProjectFile = TestHelper.GetScratchPadPath(nameof(CreateDatabaseStructure_ValidExistingFile_ThrowsStorageException));

            using (var disposeHelper = new FileDisposeHelper(tempProjectFile))
            {
                disposeHelper.LockFiles();

                // Call
                TestDelegate call = () => StorageSqliteCreator.CreateDatabaseStructure(tempProjectFile);

                // Assert
                var    exception       = Assert.Throws <ArgumentException>(call);
                string expectedMessage = $@"File '{tempProjectFile}' already exists.";
                Assert.AreEqual(expectedMessage, exception.Message);
            }
        }
Exemple #8
0
        public void Migrate_UnableToSaveAtTargetFilePath_MigrationFailsAndLogsError()
        {
            // Setup
            string sourceFilePath = ProjectMigrationTestHelper.GetOutdatedSupportedProjectFilePath();
            string targetFile     = $"{nameof(ProjectMigratorTest)}." +
                                    $"{nameof(Migrate_UnableToSaveAtTargetFilePath_MigrationFailsAndLogsError)}.rtd";
            string targetFilePath = Path.Combine(TestHelper.GetScratchPadPath(), testDirectory, targetFile);

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

            mocks.ReplayAll();

            var logDirectory = $"{nameof(Migrate_UnableToSaveAtTargetFilePath_MigrationFailsAndLogsError)}_log";

            using (new DirectoryDisposeHelper(TestHelper.GetScratchPadPath(), logDirectory))
                using (new UseCustomSettingsHelper(new TestSettingsHelper
                {
                    TempPath = TestHelper.GetScratchPadPath(logDirectory)
                }))
                    using (var fileDisposeHelper = new FileDisposeHelper(targetFilePath))
                    {
                        var migrator = new ProjectMigrator(inquiryHelper);

                        fileDisposeHelper.LockFiles();

                        var migrationSuccessful = true;

                        // Call
                        void Call() => migrationSuccessful = migrator.Migrate(sourceFilePath, targetFilePath);

                        // Assert
                        TestHelper.AssertLogMessages(Call, messages =>
                        {
                            string[] msgs = messages.ToArray();
                            Assert.AreEqual(1, msgs.Length);
                            StringAssert.StartsWith($"Het migreren van het projectbestand '{sourceFilePath}' is mislukt: ", msgs[0]);
                        });
                        Assert.IsFalse(migrationSuccessful);

                        string logPath = Path.Combine(TestHelper.GetScratchPadPath(), logDirectory, "RiskeerMigrationLog.sqlite");
                        Assert.IsFalse(File.Exists(logPath));
                    }

            mocks.VerifyAll();
        }
Exemple #9
0
        public void Write_FileInUse_ThrowCriticalFileWriteException()
        {
            // Setup
            string path = TestHelper.GetScratchPadPath(nameof(Write_FileInUse_ThrowCriticalFileWriteException));

            using (var fileDisposeHelper = new FileDisposeHelper(path))
            {
                fileDisposeHelper.LockFiles();
                TWriter writer = CreateWriterInstance(path);

                // Call
                TestDelegate call = () => writer.Write(Enumerable.Empty <IConfigurationItem>());

                // Assert
                var exception = Assert.Throws <CriticalFileWriteException>(call);
                AssertFileInUse(exception, path);
            }
        }
        public void WriteAssembly_FileInUse_ThrowsCriticalFileWriteException()
        {
            // Setup
            string filePath = TestHelper.GetScratchPadPath(nameof(WriteAssembly_FileInUse_ThrowsCriticalFileWriteException));

            using (var fileDisposeHelper = new FileDisposeHelper(filePath))
            {
                fileDisposeHelper.LockFiles();

                // Call
                void Call() => SerializableAssemblyWriter.WriteAssembly(new SerializableAssembly(), filePath);

                // Assert
                var exception = Assert.Throws <CriticalFileWriteException>(Call);
                Assert.AreEqual($"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'.", exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
        public void WriteDuneLocationCalculations_FileInUse_ThrowCriticalFileWriteException()
        {
            // Setup
            string path = TestHelper.GetScratchPadPath(nameof(WriteDuneLocationCalculations_FileInUse_ThrowCriticalFileWriteException));

            using (var fileDisposeHelper = new FileDisposeHelper(path))
            {
                fileDisposeHelper.LockFiles();

                // Call
                void Call() => DuneLocationCalculationsWriter.WriteDuneLocationCalculations(Enumerable.Empty <ExportableDuneLocationCalculation>(), path);

                // Assert
                var exception = Assert.Throws <CriticalFileWriteException>(Call);
                Assert.AreEqual($"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{path}'.", exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
Exemple #12
0
        public void Migrate_MigrationLogDatabaseInUse_MigrationFailsAndLogsError()
        {
            // Setup
            string sourceFilePath = ProjectMigrationTestHelper.GetOutdatedSupportedProjectFilePath();
            string targetFile     = $"{nameof(ProjectMigratorTest)}." +
                                    $"{nameof(Migrate_MigrationLogDatabaseInUse_MigrationFailsAndLogsError)}.rtd";
            string targetFilePath = Path.Combine(TestHelper.GetScratchPadPath(), testDirectory, targetFile);

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

            mocks.ReplayAll();

            var logDirectory = $"{nameof(Migrate_MigrationLogDatabaseInUse_MigrationFailsAndLogsError)}_log";

            string logPath = Path.Combine(TestHelper.GetScratchPadPath(), logDirectory, "RiskeerMigrationLog.sqlite");

            using (new DirectoryDisposeHelper(TestHelper.GetScratchPadPath(), logDirectory))
                using (new UseCustomSettingsHelper(new TestSettingsHelper
                {
                    TempPath = TestHelper.GetScratchPadPath(logDirectory)
                }))
                    using (var fileDisposeHelper = new FileDisposeHelper(logPath))
                    {
                        var migrator = new ProjectMigrator(inquiryHelper);
                        fileDisposeHelper.LockFiles();

                        var migrationSuccessful = true;

                        // Call
                        void Call() => migrationSuccessful = migrator.Migrate(sourceFilePath, targetFilePath);

                        // Assert
                        var logMessage = Tuple.Create(
                            $"Het is niet mogelijk om het Riskeer logbestand '{logPath}' aan te maken.",
                            LogLevelConstant.Error);
                        TestHelper.AssertLogMessageWithLevelIsGenerated(Call, logMessage);
                        Assert.IsFalse(migrationSuccessful);

                        Assert.IsTrue(File.Exists(logPath));
                    }

            mocks.VerifyAll();
        }
Exemple #13
0
        public void Migrate_ValidMigrationFileInUse_ThrowsCriticalMigrationException()
        {
            // Setup
            const string fromVersion  = "fromVersion";
            const string fromLocation = "fromLocation";
            const string toVersion    = "toVersion";

            string toLocation = TestHelper.GetScratchPadPath(nameof(Migrate_ValidMigrationFileInUse_ThrowsCriticalMigrationException));

            var mockRepository = new MockRepository();
            var comparer       = mockRepository.Stub <IComparer>();
            var versionedFile  = mockRepository.Stub <IVersionedFile>();

            versionedFile.Stub(vf => vf.Location).Return(fromLocation);
            versionedFile.Expect(vf => vf.GetVersion()).Return(fromVersion);
            mockRepository.ReplayAll();

            using (var fileDisposeHelper = new FileDisposeHelper(toLocation))
            {
                fileDisposeHelper.LockFiles();
                var migrator = new SimpleVersionedFileMigrator(comparer)
                {
                    CreateScripts =
                    {
                        new TestCreateScript(toVersion)
                    },
                    UpgradeScripts =
                    {
                        new TestUpgradeScript(fromVersion, toVersion)
                    }
                };

                // Call
                TestDelegate call = () => migrator.Migrate(versionedFile, toVersion, toLocation);

                // Assert
                var exception = Assert.Throws <CriticalMigrationException>(call);
                StringAssert.StartsWith("Het gemigreerde projectbestand is aangemaakt op '", exception.Message);
                StringAssert.EndsWith($"', maar er is een onverwachte fout opgetreden tijdens het verplaatsen naar '{toLocation}'.",
                                      exception.Message);
            }

            mockRepository.VerifyAll();
        }
Exemple #14
0
        public void ParameteredConstructor_ShapeFileIsInUse_ThrowsCriticalFileReadException()
        {
            // Setup
            string path = TestHelper.GetScratchPadPath($"{nameof(PolygonShapeFileReaderTest)}.{nameof(ParameteredConstructor_ShapeFileIsInUse_ThrowsCriticalFileReadException)}");

            using (var fileDisposeHelper = new FileDisposeHelper(path))
            {
                fileDisposeHelper.LockFiles();

                // Call
                TestDelegate call = () => new PolygonShapeFileReader(path);

                // Assert
                string expectedMessage = $"Fout bij het lezen van bestand '{path}': het bestand kon niet worden geopend. Mogelijk is het bestand corrupt of in gebruik door een andere applicatie.";
                var    exception       = Assert.Throws <CriticalFileReadException>(call);
                Assert.AreEqual(expectedMessage, exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
Exemple #15
0
        public void GetVersion_FileCannotBeRead_ThrowsCriticalFileReadException()
        {
            // Setup
            string file     = Path.GetRandomFileName();
            string filePath = TestHelper.GetScratchPadPath(file);

            var sourceFile = new ProjectVersionedFile(filePath);

            using (var fileDisposeHelper = new FileDisposeHelper(filePath))
            {
                fileDisposeHelper.LockFiles();

                // Call
                TestDelegate call = () => sourceFile.GetVersion();

                // Assert
                Assert.Throws <CriticalFileReadException>(call);
            }
        }
        public void ReadFailureMechanismSection_FileInUse_ThrowCriticalFileReadException()
        {
            // Setup
            string path = TestHelper.GetScratchPadPath(nameof(ReadFailureMechanismSection_FileInUse_ThrowCriticalFileReadException));

            using (var fileDisposeHelper = new FileDisposeHelper(path))
            {
                fileDisposeHelper.LockFiles();

                // Call
                TestDelegate call = () => new FailureMechanismSectionReader(path);

                // Assert
                string expectedMessage = $"Fout bij het lezen van bestand '{path}': het bestand kon niet worden geopend. Mogelijk is het bestand corrupt of in gebruik door een andere applicatie.";
                var    exception       = Assert.Throws <CriticalFileReadException>(call);
                Assert.AreEqual(expectedMessage, exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
Exemple #17
0
        public void CreateEmptyVersionedFile_FileExistsButNotWritable_ThrowsArgumentException()
        {
            // Setup
            const string version = "Valid version";

            string filePath     = TestHelper.GetScratchPadPath(nameof(CreateEmptyVersionedFile_FileExistsButNotWritable_ThrowsArgumentException));
            var    createScript = new TestCreateScript(version);

            using (var disposeHelper = new FileDisposeHelper(filePath))
            {
                disposeHelper.LockFiles();

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

                // Assert
                var exception = Assert.Throws <ArgumentException>(call);
                Assert.AreEqual("path", exception.ParamName);
            }
        }
        public void Constructor_FileNotWritable_ThrowsArgumentException()
        {
            // Setup
            string filePath = TestHelper.GetScratchPadPath($"{nameof(ProjectDatabaseFileTest)}.{nameof(Constructor_FileNotWritable_ThrowsArgumentException)}");

            using (var helper = new FileDisposeHelper(filePath))
            {
                helper.LockFiles();

                // Call
                TestDelegate call = () =>
                {
                    using (new ProjectDatabaseFile(filePath)) {}
                };

                // Assert
                string expectedMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'.";
                TestHelper.AssertThrowsArgumentExceptionAndTestMessage <ArgumentException>(call, expectedMessage);
            }
        }
        public void Export_CreatingZipFileThrowsCriticalFileWriteException_LogErrorAndReturnFalse()
        {
            // Setup
            string folderPath = TestHelper.GetScratchPadPath($"{nameof(MacroStabilityInwardsCalculationGroupExporterTest)}.{nameof(Export_CreatingZipFileThrowsCriticalFileWriteException_LogErrorAndReturnFalse)}");

            Directory.CreateDirectory(folderPath);
            string filePath = Path.Combine(folderPath, "test.zip");

            MacroStabilityInwardsCalculationScenario calculation1 = CreateCalculation("calculation1");

            var calculationGroup = new CalculationGroup();

            calculationGroup.Children.Add(calculation1);

            var exporter = new MacroStabilityInwardsCalculationGroupExporter(calculationGroup, new GeneralMacroStabilityInwardsInput(),
                                                                             new PersistenceFactory(), filePath, fileExtension,
                                                                             c => AssessmentSectionTestHelper.GetTestAssessmentLevel());

            try
            {
                using (new MacroStabilityInwardsCalculatorFactoryConfig())
                    using (var helper = new FileDisposeHelper(filePath))
                    {
                        helper.LockFiles();

                        // Call
                        var isExported            = true;
                        void Call() => isExported = exporter.Export();

                        // Assert
                        string expectedMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'. " +
                                                 "Er zijn geen D-GEO Suite Stability Projecten geëxporteerd.";
                        TestHelper.AssertLogMessageIsGenerated(Call, expectedMessage);
                        Assert.IsFalse(isExported);
                    }
            }
            finally
            {
                DirectoryHelper.TryDelete(folderPath);
            }
        }
Exemple #20
0
        public void Export_CreatingZipFileThrowsCriticalFileWriteException_LogErrorAndReturnFalse()
        {
            // Setup
            var assessmentSection = new AssessmentSectionStub();

            assessmentSection.SetHydraulicBoundaryLocationCalculations(new[]
            {
                new HydraulicBoundaryLocation(123, "aName", 1.1, 2.2)
            });

            string directoryPath = TestHelper.GetScratchPadPath(nameof(Export_CreatingZipFileThrowsCriticalFileWriteException_LogErrorAndReturnFalse));

            Directory.CreateDirectory(directoryPath);
            string filePath = Path.Combine(directoryPath, "test.zip");

            var exporter = new HydraulicBoundaryLocationCalculationsExporter(assessmentSection, filePath);

            try
            {
                using (var helper = new FileDisposeHelper(filePath))
                {
                    helper.LockFiles();

                    // Call
                    var isExported            = true;
                    void Call() => isExported = exporter.Export();

                    // Assert
                    string expectedMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'. " +
                                             "Er zijn geen hydraulische belastingenlocaties geëxporteerd.";
                    TestHelper.AssertLogMessageIsGenerated(Call, expectedMessage);
                    Assert.IsFalse(isExported);
                }
            }
            finally
            {
                DirectoryHelper.TryDelete(directoryPath);
            }
        }
        public void Constructor_FileInUse_ThrowCriticalFileReadException()
        {
            // Setup
            string path = TestHelper.GetScratchPadPath($"{nameof(CalculationConfigurationReaderTest)}.{nameof(Constructor_FileInUse_ThrowCriticalFileReadException)}");

            using (var fileDisposeHelper = new FileDisposeHelper(path))
            {
                fileDisposeHelper.LockFiles();

                // Call
                void Call() => new CalculationConfigurationReader(path, new[]
                {
                    new CalculationConfigurationSchemaDefinition(0, validMainSchemaDefinition, new Dictionary <string, string>(), string.Empty)
                });

                // Assert
                string expectedMessage = $"Fout bij het lezen van bestand '{path}': het bestand kon niet worden geopend. Mogelijk is het bestand corrupt of in gebruik door een andere applicatie.";
                var    exception       = Assert.Throws <CriticalFileReadException>(Call);
                Assert.AreEqual(expectedMessage, exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }
        public void Export_CreatingZipFileThrowsCriticalFileWriteException_LogsErrorAndReturnsFalse()
        {
            // Setup
            string directoryPath = TestHelper.GetScratchPadPath(nameof(Export_CreatingZipFileThrowsCriticalFileWriteException_LogsErrorAndReturnsFalse));

            Directory.CreateDirectory(directoryPath);
            string filePath = Path.Combine(directoryPath, "export.zip");

            var calculationsForTargetProbabilities = new[]
            {
                new Tuple <IEnumerable <HydraulicBoundaryLocationCalculation>, double>(
                    Enumerable.Empty <HydraulicBoundaryLocationCalculation>(), 0.1)
            };

            var exporter = new HydraulicBoundaryLocationCalculationsForTargetProbabilitiesExporter(
                calculationsForTargetProbabilities, HydraulicBoundaryLocationCalculationsType.WaterLevel, filePath);

            try
            {
                using (var helper = new FileDisposeHelper(filePath))
                {
                    helper.LockFiles();

                    // Call
                    var isExported            = true;
                    void Call() => isExported = exporter.Export();

                    // Assert
                    string expectedMessage = $"Er is een onverwachte fout opgetreden tijdens het schrijven van het bestand '{filePath}'. " +
                                             "Er zijn geen hydraulische belastingenlocaties geëxporteerd.";
                    TestHelper.AssertLogMessageIsGenerated(Call, expectedMessage);
                    Assert.IsFalse(isExported);
                }
            }
            finally
            {
                DirectoryHelper.TryDelete(directoryPath);
            }
        }
Exemple #23
0
        public void ReadWmtsConnectionInfos_FileLocked_ThrowsCriticalFileReadException()
        {
            // Setup
            string filePath = TestHelper.GetScratchPadPath(nameof(ReadWmtsConnectionInfos_FileLocked_ThrowsCriticalFileReadException));
            var    reader   = new WmtsConnectionInfoReader();

            using (var fileDisposeHelper = new FileDisposeHelper(filePath))
            {
                fileDisposeHelper.LockFiles();

                // Call
                TestDelegate call = () => reader.ReadWmtsConnectionInfos(filePath);

                // Assert
                var    exception       = Assert.Throws <CriticalFileReadException>(call);
                string expectedMessage = $"Fout bij het lezen van bestand '{filePath}': het bestand "
                                         + "kon niet worden geopend. Mogelijk is het bestand corrupt "
                                         + "of in gebruik door een andere applicatie.";
                Assert.AreEqual(expectedMessage, exception.Message);
                Assert.IsInstanceOf <IOException>(exception.InnerException);
            }
        }