public void BasicTest()
        {
            var assemblyPath        = Assembly.GetExecutingAssembly().Location.ToNPath().Parent;
            var systemUnderTestPath = assemblyPath.Combine("Minimal.Systems.dll");
            var testPath            = assemblyPath.Combine("Minimal.Tests.dll");

            // TODO: use testAssembly to scan for uses of Substitute.For and retrieve System.DateTime.Now and Class.Add

            using (var systemUnderTest = AssemblyDefinition.ReadAssembly(systemUnderTestPath))
                using (var mscorlib = AssemblyDefinition.ReadAssembly(typeof(object).Assembly.Location))
                {
                    // list of all stuff we detect an NSub extension called on it
                    var mockedMethodDefinitions = new[]
                    {
                        mscorlib.MainModule.GetType("System.DateTime").Properties.Single(p => p.Name == "Now").GetMethod,
                        systemUnderTest.MainModule.GetType("Inner").Methods.Single(m => m.Name == "Add"),
                    };

                    Patch(mockedMethodDefinitions);

                    Write(systemUnderTest, systemUnderTestPath);
                    Write(mscorlib, BaseDir.Combine("mscorlib.dll"));
                }

            // would like to do this in an appdomain but complicated
            using (ElevatedSubstitutionContext.AutoHook())
            {
                var testAssembly = Assembly.LoadFile(testPath);
                var fixtureType  = testAssembly.GetType("Fixture", true);
                var fixture      = Activator.CreateInstance(fixtureType);
                var mockMethod   = fixtureType.GetMethod("Mock");
                mockMethod.Invoke(fixture, Array.Empty <object>());
            }
        }
示例#2
0
        public void InvalidDll_Throws()
        {
            var path = BaseDir.Combine("test.txt").WriteAllText("this is definitely not a valid dll");

            File.Exists(path).ShouldBeTrue();
            Should.Throw <PeVerifyException>(() => PeVerify.Verify(path));
        }
示例#3
0
        /// <summary>
        /// Creates a full platform name, if missing. PlatformName [OS.Major Os.Minor Arch]
        /// Must match
        /// ...\Engine\Source\Programs\CrashReporter\CrashReportClient\Private\CrashDescription.cpp FCrashContext.FCrashContext
        ///</summary>
        public void SetPlatformFullName()
        {
            if (string.IsNullOrEmpty(PlatformFullName))
            {
                // Create a new one.
                string LocalPlatformName = "";
                if (BaseDir != "")
                {
                    string[] FolderComponents = BaseDir.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    if (FolderComponents.Length != 0)
                    {
                        LocalPlatformName = FolderComponents[FolderComponents.Length - 1];
                    }
                }
                else
                {
                    LocalPlatformName = PlatformNameIni;
                }

                if (!string.IsNullOrEmpty(Misc_OSVersionMajor))
                {
                    PlatformFullName = string.Format("{0} [{1} {2} {3}]",
                                                     LocalPlatformName,
                                                     Misc_OSVersionMajor,
                                                     string.IsNullOrEmpty(Misc_OSVersionMinor) ? "" : Misc_OSVersionMinor,
                                                     Misc_Is64bitOperatingSystem ? "64b" : "32b");
                }
            }
        }
            public void WhenSizeIsEqual_ThenAssertTrue()
            {
                var file1 = BaseDir.CreateFile("SizeEquals-Test1.txt");
                var file2 = BaseDir.CreateFile("SizeEquals-Test2.txt");

                Assert.DoesNotThrow(() => AssertFile.SizeEquals(file1, file2));
            }
示例#5
0
        public void ForceDeleteFile_WithNormalFile_DeletesIt()
        {
            var path = BaseDir.CreateFile("normal.txt");

            Should.NotThrow(() => SafeFile.ForceDeleteFile(path));
            path.FileExists().ShouldBeFalse();
        }
示例#6
0
            public void WhenDirectoryHasFiles_ThenAssertTrue()
            {
                BaseDir.CreateFile("Test-ContainsFiles1.txt");
                BaseDir.CreateFile("Test-ContainsFiles2.txt");

                Assert.DoesNotThrow(() => AssertDir.ContainsFiles(ExistingDirectory, 2));
            }
示例#7
0
            public void WhenDirectoryHasDirectories_ThenAssertTrue()
            {
                BaseDir.CreateDirectory("Test-ContainsDir1");
                BaseDir.CreateDirectory("Test-ContainsDir2");

                Assert.DoesNotThrow(() => AssertDir.ContainsDirectories(ExistingDirectory, 2));
            }
            public void WhenSizeIsNotEqual_ThenAssertFalse()
            {
                var file1 = BaseDir.CreateFile("SizeEquals-Test1.txt", "test1");
                var file2 = BaseDir.CreateFile("SizeEquals-Test2.txt", "test12");

                Assert.Throws <AssertionException>(() => AssertFile.SizeEquals(file1, file2));
            }
示例#9
0
 public void InitTest()
 {
     if (!BaseDir.Exists())
     {
         BaseDir.CreateDirectory();
     }
 }
        protected NPath Compile(string testAssemblyName, string sourceCode, params string[] dependentAssemblyNames)
        {
            // prefix the assembly name because they are globally unique and don't want to ever collide
            var testAssemblyPath = BaseDir
                                   .Combine($"{TestContext.CurrentContext.GetFixtureName()}_{testAssemblyName}")
                                   .ChangeExtension(".dll");

            // set up to compile

            var compiler     = new Microsoft.CSharp.CSharpCodeProvider();
            var compilerArgs = new CompilerParameters
            {
                OutputAssembly          = testAssemblyPath,
                IncludeDebugInformation = true,
                CompilerOptions         = "/o- /debug+ /warn:0"
            };

            compilerArgs.ReferencedAssemblies.Add(typeof(int).Assembly.Location); // mscorlib

            // TODO: use typecache
            var assemblies = AppDomain.CurrentDomain
                             .GetAssemblies()
                             .Where(a => !a.IsDynamic)
                             .ToDictionary(a => a.GetName().Name, a => a.Location.ToNPath(), StringComparer.OrdinalIgnoreCase);

            foreach (var dependentAssemblyName in dependentAssemblyNames)
            {
                // we may have already copied it in
                var path = BaseDir.Combine(dependentAssemblyName).ChangeExtension(".dll");

                // if not,
                if (!path.Exists() && assemblies.TryGetValue(dependentAssemblyName, out path))
                {
                    path.Copy(BaseDir.Combine(path.FileName));
                }

                compilerArgs.ReferencedAssemblies.Add(path);
            }

            // compile and handle errors

            var compilerResult = compiler.CompileAssemblyFromSource(compilerArgs, sourceCode);

            if (compilerResult.Errors.Count > 0)
            {
                var errorText = compilerResult.Errors
                                .OfType <CompilerError>()
                                .Select(e => $"({e.Line},{e.Column}): error {e.ErrorNumber}: {e.ErrorText}")
                                .Prepend("Compiler errors:")
                                .StringJoin("\n");
                throw new Exception(errorText);
            }

            testAssemblyPath.ShouldBe(new NPath(compilerResult.PathToAssembly));

            PeVerify.Verify(testAssemblyPath); // sanity check on what the compiler generated

            return(testAssemblyPath);
        }
            public void WhenFileContentIsNotExpected_ThenAssertFalse()
            {
                const string content = "test1";

                var file = BaseDir.CreateFile("ContentEquals-Test2.txt", content);

                Assert.Throws <AssertionException>(() => AssertFile.ContentEquals(file, content + "A"));
            }
            public void WhenOriginalFileDoesNotExist_AndTargetExists_ThenAssertTrue()
            {
                const string file1 = "HasMoved-File1.txt";

                BaseDir.CreateFile(file1);

                Assert.DoesNotThrow(() => AssertFile.HasMoved(DoesNotExistFile.FullName, Path.Combine(ExistingDirectoryPath, file1)));
            }
            public void WhenFileExists_ThenAssertFalse()
            {
                const string file1 = "NotExists-File1.txt";

                BaseDir.CreateFile(file1);

                Assert.Throws <AssertionException>(() => AssertFile.NotExists(Path.Combine(ExistingDirectoryPath, file1)));
            }
            public void WhenFileExists_ThenAssertTrue()
            {
                const string file1 = "Exists-File1.txt";

                BaseDir.CreateFile(file1);

                Assert.DoesNotThrow(() => AssertFile.Exists(Path.Combine(ExistingDirectoryPath, file1)));
            }
            public void WhenFileHasNotBeenModifiedSince_ThenAssertFalse()
            {
                var file = BaseDir.CreateFile("ModifiedSince-Test1.txt");

                var since = DateTime.Now;

                Assert.Throws <AssertionException>(() => AssertFile.ModifiedSince(file, since));
            }
            public void WhenFileHasBeenModifiedSince_ThenAssertTrue()
            {
                var since = DateTime.Now.AddSeconds(-1);

                var file = BaseDir.CreateFile("ModifiedSince-Test1.txt");

                Assert.DoesNotThrow(() => AssertFile.ModifiedSince(file, since));
            }
            public void WhenFileContentIsExpected_ThenAssertTrue()
            {
                const string content = "test1";

                var file = BaseDir.CreateFile("ContentEquals-Test1.txt", content);

                Assert.DoesNotThrow(() => AssertFile.ContentEquals(file, content));
            }
示例#18
0
        public void ForceDeleteFile_WithMissingFile_DoesNotThrow()
        {
            var path = BaseDir.Combine("missing.txt");

            path.FileExists().ShouldBeFalse();
            Should.NotThrow(() => SafeFile.ForceDeleteFile(path));
            path.FileExists().ShouldBeFalse();
        }
 public void ReadAllInts_WithIntsInFile_ReturnsInts()
 {
     BaseDir.Combine("1.txt").WriteAllText("0").ReadAllInts().ShouldBe(new[] { 0 });
     BaseDir.Combine("2.txt").WriteAllText("-123").ReadAllInts().ShouldBe(new[] { -123 });
     BaseDir.Combine("3.txt").WriteAllText("\n  456 \n").ReadAllInts().ShouldBe(new[] { 456 });
     BaseDir.Combine("4.txt").WriteAllText("\n  1  \r\n  2").ReadAllInts().ShouldBe(new[] { 1, 2 });
     BaseDir.Combine("5.txt").WriteAllText("\n  1    2").ReadAllInts().ShouldBe(new[] { 1, 2 });
     BaseDir.Combine("6.txt").WriteAllText("\n  1    2\n ").ReadAllInts().ShouldBe(new[] { 1, 2 });
 }
示例#20
0
        public void ForceDeleteFile_WithReadOnlyFile_DeletesIt()
        {
            var path = BaseDir.CreateFile("readonly.txt");

            SafeFile.SetReadOnly(path);

            Should.NotThrow(() => SafeFile.ForceDeleteFile(path));
            path.FileExists().ShouldBeFalse();
        }
示例#21
0
        public void Format_WithoutPackageRootSpecified_DoesNotThrow()
        {
            var logger = new StringLogger();

            App.Execute(new[] { "format", BaseDir.Combine("file").WriteAllText("") }, logger);

            logger.ErrorsAsString.ShouldBeEmpty();
            logger.InfosAsString.ShouldBeEmpty();
        }
示例#22
0
        public void AtomicWrite_ReplacingExistingReadOnlyFile_Throws()
        {
            var path = BaseDir.CreateFile("test.txt");

            SafeFile.SetReadOnly(path);

            Should.Throw <UnauthorizedAccessException>(() =>
                                                       SafeFile.AtomicWrite(path, tmpPath => tmpPath.ToNPath().CreateFile()));
        }
 public void ReadAllFloats_WithFloatsInFile_ReturnsFloats()
 {
     BaseDir.Combine("1.txt").WriteAllText("0").ReadAllFloats().ShouldBe(new[] { 0f });
     BaseDir.Combine("2.txt").WriteAllText("-123.456").ReadAllFloats().ShouldBe(new[] { -123.456f });
     BaseDir.Combine("3.txt").WriteAllText("\n  456.789 \n").ReadAllFloats().ShouldBe(new[] { 456.789f });
     BaseDir.Combine("4.txt").WriteAllText("\n  1.2  \r\n  2.3").ReadAllFloats().ShouldBe(new[] { 1.2f, 2.3f });
     BaseDir.Combine("5.txt").WriteAllText("\n  1.3    2.4").ReadAllFloats().ShouldBe(new[] { 1.3f, 2.4f });
     BaseDir.Combine("6.txt").WriteAllText("\n  1.4    2.5\n ").ReadAllFloats().ShouldBe(new[] { 1.4f, 2.5f });
 }
示例#24
0
        private void Browse_Click(object sender, EventArgs e)
        {
            DialogResult result = BaseDir.ShowDialog();

            if (result == DialogResult.OK)
            {
                baseDirectory = BaseDir.SelectedPath;
                rootPath.Text = baseDirectory;
            }
        }
示例#25
0
        public void Format_WithNoEditorConfig_DoesNothing()
        {
            var path = BaseDir.Combine("file.txt").WriteAllText(k_UnformattedSource);

            var result = Execute("format", path);

            result.ErrorsAsString.ShouldBeEmpty();
            result.InfosAsString.ShouldBeEmpty();
            path.ReadAllText().ShouldBe(k_UnformattedSource);
        }
示例#26
0
        public void AtomicWrite_WithEmptyAction_ShouldDoNothing()
        {
            var path = BaseDir.CreateFile("test.txt");

            SafeFile.AtomicWrite(path, tmpPath => { });

            path.FileExists().ShouldBeTrue();
            (path + SafeFile.TmpExtension).ToNPath().FileExists().ShouldBeFalse();
            (path + SafeFile.BakExtension).ToNPath().FileExists().ShouldBeFalse();
        }
示例#27
0
        public void Format_WithEditorConfig_FormatsFile()
        {
            WriteRootEditorConfig("[*]", "formatters=uncrustify,generic");
            var path = BaseDir.Combine("file.cs").WriteAllText(k_UnformattedSource);

            var result = Execute("format", path);

            result.ErrorsAsString.ShouldBeEmpty();
            result.InfosAsString.ShouldBeEmpty();
            path.ReadAllText().ShouldBe(k_FormattedSource);
        }
示例#28
0
        public void SetReadOnly_AppliesProperFileAttributes()
        {
            var path = BaseDir.CreateFile("normal.txt");

            ((File.GetAttributes(path) & FileAttributes.ReadOnly) == 0).ShouldBeTrue();

            SafeFile.SetReadOnly(path);
            ((File.GetAttributes(path) & FileAttributes.ReadOnly) != 0).ShouldBeTrue();
            SafeFile.SetReadOnly(path, false);
            ((File.GetAttributes(path) & FileAttributes.ReadOnly) == 0).ShouldBeTrue();
        }
示例#29
0
        public void Format_WithBadPackagePath_ReturnsError()
        {
            // minimum required to trigger need for coding package guts
            WriteRootEditorConfig("[*]", "formatters=uncrustify");

            var logger = new StringLogger();

            App.Execute(new[]
            {
                "format", "--package-root", "does_not_exist",
                BaseDir.Combine("file").WriteAllText("")
            }, logger);

            logger.ErrorsAsString.ShouldContain("Invalid package root");
        }
示例#30
0
        public void AtomicWrite_WithExistingReadOnlyTempAndBakFiles_OverwritesFilesAndOperatesNormally()
        {
            var path   = BaseDir.Combine("test.txt").WriteAllText("test");
            var temp   = (path + SafeFile.TmpExtension).ToNPath().CreateFile();
            var backup = (path + SafeFile.BakExtension).ToNPath().CreateFile();

            SafeFile.SetReadOnly(temp);
            SafeFile.SetReadOnly(backup);

            SafeFile.AtomicWrite(path, tmpPath => tmpPath.ToNPath().WriteAllText("new"));

            temp.FileExists().ShouldBeFalse();
            backup.FileExists().ShouldBeFalse();
            path.ReadAllText().ShouldBe("new");
        }