Beispiel #1
0
        public void CanResolveMultipleLevelsOfDependencies()
        {
            var inputPackage  = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
            var outputPackage = Path.GetTempFileName() + ".nupkg";
            var sourceDir     = IntegrationTestHelper.GetPath("fixtures", "packages");

            var fixture = new ReleasePackage(inputPackage);

            (new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();

            try {
                fixture.CreateReleasePackage(outputPackage, sourceDir);

                this.Log().Info("Resulting package is at {0}", outputPackage);
                var pkg = new ZipPackage(outputPackage);

                int refs = pkg.FrameworkAssemblies.Count();
                this.Log().Info("Found {0} refs", refs);
                refs.ShouldEqual(0);

                this.Log().Info("Files in release package:");
                pkg.GetFiles().ForEach(x => this.Log().Info(x.Path));

                var filesToLookFor = new[] {
                    "xunit.assert.dll",         // Tests => Xunit => Xunit.Assert
                    "NuGet.Core.dll",           // Tests => NuGet
                    "Squirrel.Tests.dll",
                };

                filesToLookFor.ForEach(name => {
                    this.Log().Info("Looking for {0}", name);
                    pkg.GetFiles().Any(y => y.Path.ToLowerInvariant().Contains(name.ToLowerInvariant())).ShouldBeTrue();
                });
            } finally {
                File.Delete(outputPackage);
            }
        }
        public void CorruptedReleaseFileMeansWeStartFromScratch()
        {
            string localPackagesDir  = Path.Combine(".", "theApp", "packages");
            string localReleasesFile = Path.Combine(localPackagesDir, "RELEASES");

            var fileInfo = new Mock <FileInfoBase>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.OpenRead())
            .Returns(new MemoryStream(Encoding.UTF8.GetBytes("lol this isn't right")));

            var dirInfo = new Mock <DirectoryInfoBase>();

            dirInfo.Setup(x => x.Exists).Returns(true);

            var fs = new Mock <IFileSystemFactory>();

            fs.Setup(x => x.GetFileInfo(localReleasesFile)).Returns(fileInfo.Object);
            fs.Setup(x => x.CreateDirectoryRecursive(localPackagesDir)).Verifiable();
            fs.Setup(x => x.DeleteDirectoryRecursive(localPackagesDir)).Verifiable();
            fs.Setup(x => x.GetDirectoryInfo(localPackagesDir)).Returns(dirInfo.Object);

            var urlDownloader = new Mock <IUrlDownloader>();
            var dlPath        = IntegrationTestHelper.GetPath("fixtures", "RELEASES-OnePointOne");

            urlDownloader.Setup(x => x.DownloadUrl(It.IsAny <string>(), It.IsAny <IObserver <int> >()))
            .Returns(Observable.Return(File.ReadAllText(dlPath, Encoding.UTF8)));

            var fixture = new UpdateManager("http://lol", "theApp", FrameworkVersion.Net40, ".", fs.Object, urlDownloader.Object);

            using (fixture) {
                fixture.CheckForUpdate().First();
            }

            fs.Verify(x => x.CreateDirectoryRecursive(localPackagesDir), Times.Once());
            fs.Verify(x => x.DeleteDirectoryRecursive(localPackagesDir), Times.Once());
        }
Beispiel #3
0
            Returns_400_If_Request_Authorized_But_Invalid()
            {
                // Arrange
                Guid[] keys       = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
                var    requestKey = keys[1];
                var    config     = IntegrationTestHelper
                                    .GetInitialIntegrationTestConfig(GetContainer(keys));

                var shipmentTypeRequestModel = new ShipmentTypeRequestModel {
                    Name  = "ANameWhichIsMoreThan50CharsANameWhichIsMoreThan50Chars",
                    Price = 40.00M
                };

                var request = HttpRequestMessageHelper
                              .ConstructRequest(
                    httpMethod: HttpMethod.Put,
                    uri: string.Format(
                        "https://localhost/{0}/{1}",
                        "api/shipmenttypes", requestKey),
                    mediaType: "application/json",
                    username: Constants.ValidAdminUserName,
                    password: Constants.ValidAdminPassword);

                request.Content = new ObjectContent <ShipmentTypeRequestModel>(
                    shipmentTypeRequestModel, new JsonMediaTypeFormatter());

                // Act
                var httpError = await IntegrationTestHelper
                                .GetResponseMessageBodyAsync <HttpError>(
                    config, request, HttpStatusCode.BadRequest);

                var modelState = (HttpError)httpError["ModelState"];
                var nameError  = modelState["requestModel.Name"] as string[];

                // Assert
                Assert.NotNull(nameError);
            }
Beispiel #4
0
        public void ChecksumShouldFailIfFilesAreBogus()
        {
            var filename      = "Squirrel.Core.1.0.0.0.nupkg";
            var nuGetPkg      = IntegrationTestHelper.GetPath("fixtures", filename);
            var fs            = new Mock <IFileSystemFactory>();
            var urlDownloader = new Mock <IUrlDownloader>();

            ReleaseEntry entry;

            using (var f = File.OpenRead(nuGetPkg)) {
                entry = ReleaseEntry.GenerateFromFile(f, filename);
            }

            var fileInfo = new Mock <FileInfoBase>();

            fileInfo.Setup(x => x.OpenRead()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("Lol broken")));
            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.Length).Returns(new FileInfo(nuGetPkg).Length);
            fileInfo.Setup(x => x.Delete()).Verifiable();

            fs.Setup(x => x.GetFileInfo(Path.Combine(".", "theApp", "packages", filename))).Returns(fileInfo.Object);

            var fixture = ExposedObject.From(
                new UpdateManager("http://lol", "theApp", FrameworkVersion.Net40, ".", fs.Object, urlDownloader.Object));

            bool shouldDie = true;

            try {
                fixture.checksumPackage(entry);
            } catch (Exception ex) {
                this.Log().InfoException("Checksum failure", ex);
                shouldDie = false;
            }

            shouldDie.ShouldBeFalse();
            fileInfo.Verify(x => x.Delete(), Times.Once());
        }
        public async Task GivenInvalidUserId_ReturnHttpStatusCodeOK_andNewConversationWithEmptyListMessage()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context = _factory.InitializeDbForTests();
            var command = new CreateConversationCommand()
            {
                Type    = "pair",
                Members = new List <UserModel>()
                {
                    new UserModel()
                    {
                        UserId      = new Guid("020cdee0-8ecd-408a-b662-cd4d9cdf0100"),
                        DisplayName = "TestUser1"
                    },
                    new UserModel()
                    {
                        UserId      = Guid.NewGuid(),
                        DisplayName = "TestUser2"
                    }
                },
            };
            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/Conversation/CreateOrGet/", content);

            response.EnsureSuccessStatusCode();

            var vm = await IntegrationTestHelper.GetResponseContent <ConversationMessageModel>(response);

            vm.ShouldBeOfType <ConversationMessageModel>();
            vm.Conversation.ShouldNotBeNull();
            vm.LstMessageChat.Count.ShouldBe(0);
            // release DB
            _factory.DisposeDbForTests(context);
        }
        public async Task GivenValidUserId_ReturnConversationMessageModel_HaveMessageList()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context = _factory.InitializeDbForTests();
            var command = new CreateConversationCommand()
            {
                Type    = "pair",
                Members = new List <UserModel>()
                {
                    new UserModel()
                    {
                        UserId      = new Guid("9c7ff9c5-90bd-4207-9dff-01da2ceece21"),
                        DisplayName = "TestUser4"
                    },
                    new UserModel()
                    {
                        UserId      = new Guid("020cdee0-8ecd-408a-b662-cd4d9cdf0100"),
                        DisplayName = "TestUser5"
                    }
                },
            };
            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/Conversation/CreateOrGet/", content);

            response.EnsureSuccessStatusCode();

            var vm = await IntegrationTestHelper.GetResponseContent <ConversationMessageModel>(response);

            vm.ShouldBeOfType <ConversationMessageModel>();
            vm.Conversation.Id.ShouldBe(new Guid("b73477a4-f61d-46fa-873c-7d71c01dfbd2"));
            vm.LstMessageChat.Count.ShouldBe(1);
            // release DB
            _factory.DisposeDbForTests(context);
        }
Beispiel #7
0
            Returns_200_And_Updated_ShipmentType_If_Request_Authorized_But_Request_Is_Valid()
            {
                // Arrange
                Guid[] keys       = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
                var    requestKey = keys[1];
                var    config     = IntegrationTestHelper
                                    .GetInitialIntegrationTestConfig(GetContainer(keys));

                var shipmentTypeRequestModel = new ShipmentTypeRequestModel {
                    Name  = "X-Large",
                    Price = 40.00M
                };

                var request = HttpRequestMessageHelper
                              .ConstructRequest(
                    httpMethod: HttpMethod.Put,
                    uri: string.Format(
                        "https://localhost/{0}/{1}",
                        "api/shipmenttypes", requestKey),
                    mediaType: "application/json",
                    username: Constants.ValidAdminUserName,
                    password: Constants.ValidAdminPassword);

                request.Content = new ObjectContent <ShipmentTypeRequestModel>(
                    shipmentTypeRequestModel, new JsonMediaTypeFormatter());

                // Act
                var shipmentTypeDto = await IntegrationTestHelper
                                      .GetResponseMessageBodyAsync <ShipmentTypeDto>(
                    config, request, HttpStatusCode.OK);

                // Assert
                Assert.Equal(requestKey, shipmentTypeDto.Key);
                Assert.Equal(shipmentTypeRequestModel.Name, shipmentTypeDto.Name);
                Assert.Equal(shipmentTypeRequestModel.Price, shipmentTypeDto.Price);
            }
Beispiel #8
0
            Returns_409_If_Request_Authorized_But_Conflicted()
            {
                // Arrange
                var shipmentTypes = GetDummyShipmentTypes(new[] {
                    Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()
                });
                var targetShipmentType = shipmentTypes.FirstOrDefault();
                var config             = IntegrationTestHelper
                                         .GetInitialIntegrationTestConfig(
                    GetContainer(shipmentTypes));

                var shipmentTypeRequestModel = new ShipmentTypeRequestModel {
                    Name  = targetShipmentType.Name,
                    Price = 40.00M
                };

                var request = HttpRequestMessageHelper
                              .ConstructRequest(
                    httpMethod: HttpMethod.Post,
                    uri: string.Format(
                        "https://localhost/{0}",
                        "api/shipmenttypes"),
                    mediaType: "application/json",
                    username: Constants.ValidAdminUserName,
                    password: Constants.ValidAdminPassword);

                request.Content = new ObjectContent <ShipmentTypeRequestModel>(
                    shipmentTypeRequestModel, new JsonMediaTypeFormatter());

                // Act
                var response = await IntegrationTestHelper
                               .GetResponseAsync(config, request);

                // Assert
                Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
            }
Beispiel #9
0
        public async Task GivenInvalidCreateTeamCommand_ReturnsBadRequest()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new CreateTeamCommand
            {
                Name        = "This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length.",
                Description = "Des A",
                Users       = new List <UserModel>
                {
                    new UserModel()
                    {
                        UserId      = Guid.NewGuid(),
                        DisplayName = "TestUser1"
                    }
                }
            };

            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/team", content);

            response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
        }
Beispiel #10
0
        public async Task GivenValidCreateTeamCommand_ReturnsSuccessCode()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new CreateTeamCommand
            {
                Name        = "Team A.",
                Description = "Des A",
                Users       = new List <UserModel>
                {
                    new UserModel()
                    {
                        UserId      = Guid.NewGuid(),
                        DisplayName = "TestUser1"
                    }
                }
            };

            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync($"/api/team", content);

            response.EnsureSuccessStatusCode();
        }
Beispiel #11
0
        public async Task GivenValidKeyword_ShouldReturnUsersList2()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context = _factory.InitializeDbForTests();
            var keyword = "User";

            var response = await client.GetAsync($"/api/Search/users?keyword={keyword}");

            response.EnsureSuccessStatusCode();

            List <SearchModel> vm = await IntegrationTestHelper.GetResponseContent <List <SearchModel> >(response);

            vm.ShouldBeOfType <List <SearchModel> >();
            vm.ShouldNotBeEmpty();
            foreach (var m in vm)
            {
                m.Name.ShouldContain(keyword);
            }

            // release DB
            _factory.DisposeDbForTests(context);
        }
Beispiel #12
0
        public async Task GivenValidCreatePersonCommand_ReturnsSuccessCode()
        {
            // Arrange
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new CreatePersonCommand()
            {
                FirstName = "fname",
                LastName  = "lname",
                Address   = "addr",
                City      = "city",
                State     = "st",
                Zip       = "12345",
                BirthDate = DateTime.Now
            };

            var context = IntegrationTestHelper.GetRequestContent(command);

            // Act
            var response = await client.PostAsync("/api/persons", context);

            // Assert
            response.EnsureSuccessStatusCode();
        }
        public async Task GivenValidRequestWithIsPin_ShouldUpdateMessage()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context = _factory.InitializeDbForTests();

            var messageId = Guid.Parse("b73477a4-f61d-46fa-873c-7d71c01dfbdf");

            UpdateMessageChatCommand command = new UpdateMessageChatCommand()
            {
                MessageId = Guid.Parse("b73477a4-f61d-46fa-873c-7d71c01dfbdf"),
                IsPin     = true,
            };
            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PutAsync($"/api/Messages/{messageId}", content);

            response.EnsureSuccessStatusCode();
            response.StatusCode.ShouldBe(HttpStatusCode.OK);

            // release DB
            _factory.DisposeDbForTests(context);
        }
        public async Task CreateShortcutsRoundTrip()
        {
            string remotePkgPath;
            string path;

            using (Utility.WithTempDirectory(out path)) {
                using (Utility.WithTempDirectory(out remotePkgPath))
                    using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
                        IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
                        await mgr.FullInstall();
                    }

                var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp"));
                fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot, false, null, null);

                // NB: COM is Weird.
                Thread.Sleep(1000);
                fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot);

                // NB: Squirrel-Aware first-run might still be running, slow
                // our roll before blowing away the temp path
                Thread.Sleep(1000);
            }
        }
Beispiel #15
0
            public async Task Returns_201_And_ShipmentState_If_Request_Authorized_And_Success()
            {
                // Arrange
                Guid[] shipmentKeys     = IntegrationTestHelper.GetKeys(9);
                var    validshipmentKey = shipmentKeys[1];

                var shipmentStateRequestModel = new ShipmentStateRequestModel {
                    ShipmentStatus = "InTransit"
                };

                var configAndRequest = GetConfigAndRequestMessage(
                    shipmentKeys, validshipmentKey, shipmentStateRequestModel);

                // Act
                var shipmentStateDto = await IntegrationTestHelper
                                       .GetResponseMessageBodyAsync <ShipmentStateDto>(
                    configAndRequest.Item1,
                    configAndRequest.Item2,
                    HttpStatusCode.Created);

                // Assert
                Assert.Equal(shipmentStateRequestModel.ShipmentStatus, shipmentStateDto.ShipmentStatus);
                Assert.Equal(validshipmentKey, shipmentStateDto.ShipmentKey);
            }
Beispiel #16
0
            public async Task Returns_404_If_Request_Authorized_But_Shipment_Does_Not_Exist()
            {
                // Arrange
                var shipmentKeys  = IntegrationTestHelper.GetKeys(9);
                var affiliateKeys = IntegrationTestHelper.GetKeys(3);

                // Except for first key, all keys are not
                // related to current Affiliate user
                var validAffiliateKey = affiliateKeys[0];

                var invalidShipmetKey = Guid.NewGuid();

                // Get the config and request
                var configAndRequest = GetConfigAndRequestMessage(
                    shipmentKeys, affiliateKeys, validAffiliateKey, invalidShipmetKey);

                // Act
                var response = await IntegrationTestHelper
                               .GetResponseAsync(
                    configAndRequest.Item1, configAndRequest.Item2);

                // Assert
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        public async Task FullUninstallRemovesAllVersions()
        {
            string tempDir;
            string remotePkgDir;

            using (Utility.WithTempDirectory(out tempDir))
                using (Utility.WithTempDirectory(out remotePkgDir)) {
                    IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
                    var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
                    ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));

                    using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                        await fixture.FullInstall();
                    }

                    await Task.Delay(1000);

                    IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
                    pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
                    ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));

                    using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                        await fixture.UpdateApp();
                    }

                    await Task.Delay(1000);

                    using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
                        await fixture.FullUninstall();
                    }

                    Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));
                    Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));
                    Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", ".dead")));
                }
        }
Beispiel #18
0
            public async Task Returns_200_If_Request_Authanticated_And_Affiliate_Is_Related_To_Current_User()
            {
                // Arrange
                var shipmentKeys  = IntegrationTestHelper.GetKeys(9);
                var affiliateKeys = IntegrationTestHelper.GetKeys(3);

                // except for first key, all keys are not
                // related to current Affiliate user
                var validAffiliateKey = affiliateKeys[0];

                // get the mock seperately. We will verify the method calls
                var shipments       = GetDummyShipments(shipmentKeys, affiliateKeys);
                var affiliates      = GetDummyAffiliates(affiliateKeys);
                var shipmentSrvMock = GetShipmentSrvMock(shipments, affiliates);

                var config = IntegrationTestHelper
                             .GetInitialIntegrationTestConfig(
                    GetContainerThroughMock(shipmentSrvMock));

                var request = HttpRequestMessageHelper
                              .ConstructRequest(
                    httpMethod: HttpMethod.Get,
                    uri: string.Format(
                        "https://localhost/{0}?page={1}&take={2}",
                        string.Format(ApiBaseRequestPathFormat, validAffiliateKey), 1, 2),
                    mediaType: "application/json",
                    username: Constants.ValidAffiliateUserName,
                    password: Constants.ValidAffiliatePassword);

                // Act
                var response = await IntegrationTestHelper
                               .GetResponseAsync(config, request);

                // Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
Beispiel #19
0
        public void DownloadReleasesFromFileDirectoryIntegrationTest()
        {
            string tempDir = null;

            var updateDir = new DirectoryInfo(IntegrationTestHelper.GetPath("..", "SampleUpdatingApp", "SampleReleasesFolder"));

            var entriesToDownload = updateDir.GetFiles("*.nupkg")
                                    .Select(x => ReleaseEntry.GenerateFromFile(x.FullName))
                                    .ToArray();

            entriesToDownload.Count().ShouldBeGreaterThan(0);

            using (Utility.WithTempDirectory(out tempDir)) {
                // NB: This is normally done by CheckForUpdates, but since
                // we're skipping that in the test we have to do it ourselves
                (new DirectoryInfo(Path.Combine(tempDir, "SampleUpdatingApp", "packages"))).CreateRecursive();

                var fixture = new UpdateManager(updateDir.FullName, "SampleUpdatingApp", FrameworkVersion.Net40, tempDir);
                using (fixture.AcquireUpdateLock()) {
                    var progress = fixture.DownloadReleases(entriesToDownload).ToList().First();
                    this.Log().Info("Progress: [{0}]", String.Join(",", progress));
                    progress.Buffer(2, 1).All(x => x.Count != 2 || x[1] > x[0]).ShouldBeTrue();
                    progress.Last().ShouldEqual(100);
                }

                entriesToDownload.ForEach(x => {
                    this.Log().Info("Looking for {0}", x.Filename);
                    var actualFile = Path.Combine(tempDir, "SampleUpdatingApp", "packages", x.Filename);
                    File.Exists(actualFile).ShouldBeTrue();

                    var actualEntry = ReleaseEntry.GenerateFromFile(actualFile);
                    actualEntry.SHA1.ShouldEqual(x.SHA1);
                    actualEntry.Version.ShouldEqual(x.Version);
                });
            }
        }
Beispiel #20
0
        public void InstallWithContentInPackageDropsInSameFolder()
        {
            string dir;
            string outDir;

            var package = "ProjectWithContent.1.0.0.0-beta-full.nupkg";

            using (Utility.WithTempDirectory(out outDir))
                using (IntegrationTestHelper.WithFakeInstallDirectory(package, out dir))
                {
                    try
                    {
                        var di = new DirectoryInfo(dir);

                        var bundledRelease = ReleaseEntry.GenerateFromFile(di.GetFiles("*.nupkg").First().FullName);
                        var fixture        = new InstallManager(bundledRelease, outDir);
                        var pkg            = new ZipPackage(Path.Combine(dir, package));

                        fixture.ExecuteInstall(dir, pkg).Wait();

                        var filesToLookFor = new[] {
                            "ProjectWithContent\\app-1.0.0.0\\project-with-content.exe",
                            "ProjectWithContent\\app-1.0.0.0\\some-words.txt",
                            "ProjectWithContent\\app-1.0.0.0\\dir\\item-in-subdirectory.txt",
                            "ProjectWithContent\\packages\\RELEASES",
                            "ProjectWithContent\\packages\\ProjectWithContent.1.0.0.0-beta-full.nupkg",
                        };

                        filesToLookFor.ForEach(f => Assert.True(File.Exists(Path.Combine(outDir, f)), "Could not find file: " + f));
                    }
                    finally
                    {
                        Directory.Delete(dir, true);
                    }
                }
        }
Beispiel #21
0
        public async Task GivenTaskItemIdDifferId_ReturnsNotFound()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new UpdateTaskItemCommand
            {
                Id          = new Guid("197d0438-e04b-453d-b5de-eca05960c6ae"),
                Name        = "TaskItem 1",
                Description = "Des11111",
                CreatedBy   = new UserModel()
                {
                    UserId      = Guid.NewGuid(),
                    DisplayName = "TestUser1"
                },
                TeamId = new Guid("197d0438-e04b-453d-b5de-eca05960c6ae"),
                Status = 2
            };

            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PutAsync($"/api/TaskItems/Update/{Guid.NewGuid()}", content);

            response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
        }
Beispiel #22
0
 private static IEnumerable <Shipment> GetDummyShipments(
     Guid[] shipmentKeys, Guid[] affiliateKeys)
 {
     return(GetDummyShipments(
                shipmentKeys, affiliateKeys, IntegrationTestHelper.GetKeys(3)));
 }
Beispiel #23
0
 public async Task Delete_validId_shouldDeleteAccount()
 {
     var client = CreateClient();
     await client.Delete(IntegrationTestHelper.ReadHmacSettings().UserId);
 }
        public void CreateDeltaPackageIntegrationTest()
        {
            var basePackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
            var newPackage  = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.2.0-pre.nupkg");

            var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");

            (new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();

            var baseFixture = new ReleasePackage(basePackage);
            var fixture     = new ReleasePackage(newPackage);

            var tempFiles = Enumerable.Range(0, 3)
                            .Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
                            .ToArray();

            try {
                baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
                fixture.CreateReleasePackage(tempFiles[1], sourceDir);

                (new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
                (new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();

                var deltaBuilder = new DeltaPackageBuilder();
                deltaBuilder.CreateDeltaPackage(baseFixture, fixture, tempFiles[2]);

                var fullPkg  = new ZipPackage(tempFiles[1]);
                var deltaPkg = new ZipPackage(tempFiles[2]);

                //
                // Package Checks
                //

                fullPkg.Id.ShouldEqual(deltaPkg.Id);
                fullPkg.Version.CompareTo(deltaPkg.Version).ShouldEqual(0);

                // Delta packages should be smaller than the original!
                var fileInfos = tempFiles.Select(x => new FileInfo(x)).ToArray();
                this.Log().Info("Base Size: {0}, Current Size: {1}, Delta Size: {2}",
                                fileInfos[0].Length, fileInfos[1].Length, fileInfos[2].Length);

                (fileInfos[2].Length - fileInfos[1].Length).ShouldBeLessThan(0);

                //
                // File Checks
                ///

                var deltaPkgFiles = deltaPkg.GetFiles().ToList();
                deltaPkgFiles.Count.ShouldBeGreaterThan(0);

                this.Log().Info("Files in delta package:");
                deltaPkgFiles.ForEach(x => this.Log().Info(x.Path));

                var newFilesAdded = new[] {
                    "Newtonsoft.Json.dll",
                    "Refit.dll",
                    "Refit-Portable.dll",
                    "Castle.Core.dll",
                }.Select(x => x.ToLowerInvariant());

                // vNext adds a dependency on Refit
                newFilesAdded
                .All(x => deltaPkgFiles.Any(y => y.Path.ToLowerInvariant().Contains(x)))
                .ShouldBeTrue();

                // All the other files should be diffs and shasums
                deltaPkgFiles
                .Where(x => !newFilesAdded.Any(y => x.Path.ToLowerInvariant().Contains(y)))
                .All(x => x.Path.ToLowerInvariant().EndsWith("diff") || x.Path.ToLowerInvariant().EndsWith("shasum"))
                .ShouldBeTrue();

                // Every .diff file should have a shasum file
                deltaPkg.GetFiles().Any(x => x.Path.ToLowerInvariant().EndsWith(".diff")).ShouldBeTrue();
                deltaPkg.GetFiles()
                .Where(x => x.Path.ToLowerInvariant().EndsWith(".diff"))
                .ForEach(x => {
                    var lookingFor = x.Path.Replace(".diff", ".shasum");
                    this.Log().Info("Looking for corresponding shasum file: {0}", lookingFor);
                    deltaPkg.GetFiles().Any(y => y.Path == lookingFor).ShouldBeTrue();
                });
            } finally {
                tempFiles.ForEach(File.Delete);
            }
        }
Beispiel #25
0
        public void ApplyMultipleDeltaPackagesGeneratesCorrectHash()
        {
            var firstRelease  = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "SquirrelDesktopDemo-1.0.0-full.nupkg"), true);
            var secondRelease = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "SquirrelDesktopDemo-1.1.0-full.nupkg"), true);
            var thirdRelease  = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "SquirrelDesktopDemo-1.2.0-full.nupkg"), true);

            string installDir, releasesDir;

            using (Utility.WithTempDirectory(out releasesDir))
                using (IntegrationTestHelper.WithFakeAlreadyInstalledApp("InstalledSquirrelDesktopDemo-1.0.0.zip", out installDir)) {
                    var firstDelta  = Path.Combine(releasesDir, "SquirrelDesktopDemo-1.1.0-delta.nupkg");
                    var secondDelta = Path.Combine(releasesDir, "SquirrelDesktopDemo-1.2.0-delta.nupkg");


                    new[] { firstRelease, secondRelease, thirdRelease }
                    .ForEach(file =>
                    {
                        var packageFile = file.ReleasePackageFile;
                        var fileName    = Path.GetFileName(packageFile);
                        File.Copy(packageFile, Path.Combine(releasesDir, fileName));
                    });

                    var deltaBuilder = new DeltaPackageBuilder();
                    deltaBuilder.CreateDeltaPackage(firstRelease, secondRelease, firstDelta);
                    deltaBuilder.CreateDeltaPackage(secondRelease, thirdRelease, secondDelta);

                    ReleaseEntry.BuildReleasesFile(releasesDir);

                    var updateManager = new UpdateManager(
                        releasesDir, "ShimmerDesktopDemo", FrameworkVersion.Net40, installDir);

                    using (updateManager) {
                        var updateInfo = updateManager.CheckForUpdate().First();

                        Assert.Equal(2, updateInfo.ReleasesToApply.Count());

                        updateManager.DownloadReleases(updateInfo.ReleasesToApply).Wait();
                        updateManager.ApplyReleases(updateInfo).Wait();
                    }

                    string referenceDir;
                    using (IntegrationTestHelper.WithFakeAlreadyInstalledApp("InstalledSquirrelDesktopDemo-1.2.0.zip", out referenceDir)) {
                        var referenceVersion = Path.Combine(referenceDir, "ShimmerDesktopDemo", "app-1.2.0");
                        var installVersion   = Path.Combine(installDir, "ShimmerDesktopDemo", "app-1.2.0");

                        var referenceFiles = Directory.GetFiles(referenceVersion);
                        var actualFiles    = Directory.GetFiles(installVersion);

                        Assert.Equal(referenceFiles.Count(), actualFiles.Count());

                        var invalidFiles =
                            Enumerable.Zip(referenceFiles, actualFiles,
                                           (reference, actual) => {
                            var refSha    = Utility.CalculateFileSHA1(reference);
                            var actualSha = Utility.CalculateFileSHA1(actual);

                            return(new { File = actual, Result = refSha == actualSha });
                        })
                            .Where(c => !c.Result).ToArray();

                        Assert.Empty(invalidFiles);
                    }
                }
        }
        public void Setup()
        {
            var rootContainer = IntegrationTestHelper.SetUp().Build();

            _factory = rootContainer.Resolve <IUnitOfWorkFactory <IVotingCandidateRepository, IVoteRepository, ISongRepository> >();
        }
        public async Task GivenValidRequestWithAttachfile_ShouldUpdateTaskWithAttachfile()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            // init DB for test
            var context = _factory.InitializeDbForTests();

            var listAttachFiles = new List <AttachFileModel>();

            // Mock Attachfile 1
            var formData1       = _factory.MockUploadFileAction("file1.txt", "data file 1");
            var uploadResponse1 = await client.PostAsync($"/api/Upload/", formData1);

            var fileAfterUpload1 = await IntegrationTestHelper.GetResponseContent <FileListDto>(uploadResponse1);

            listAttachFiles.Add(new AttachFileModel()
            {
                FileName        = fileAfterUpload1.Files[0].FileName,
                FileStorageName = fileAfterUpload1.Files[0].FileStorageName,
                BlobStorageUrl  = fileAfterUpload1.Files[0].BlobStorageUrl,
                FileSize        = fileAfterUpload1.Files[0].FileSize,
                ThumbnailImage  = fileAfterUpload1.Files[0].ThumbnailImage,
                LocalUrl        = fileAfterUpload1.Files[0].LocalUrl
            });
            string taskId = "197d0438-e04b-453d-b5de-eca05960c6ae";
            UpdateTaskItemCommand command1 = new UpdateTaskItemCommand()
            {
                Name        = "Task With AttachFiles",
                Description = "Description Test",
                TeamId      = Guid.Parse(taskId),
                AttachFiles = listAttachFiles,
                Assignee    = new UserModel()
                {
                    UserId = Guid.NewGuid(), DisplayName = Guid.NewGuid().ToString()
                },
                Deadline  = DateTime.UtcNow,
                Id        = new Guid(taskId),
                Status    = '2',
                Tags      = new List <TagModel>(),
                Relations = new List <RelatedObjectModel>()
            };

            var content1 = IntegrationTestHelper.GetRequestContent(command1);

            var response1 = await client.PutAsync($"/api/TaskItems/Update/{taskId}", content1);

            response1.EnsureSuccessStatusCode();

            // Mock Attachfile 2
            var formData2       = _factory.MockUploadFileAction("file2.txt", "data file 2");
            var uploadResponse2 = await client.PostAsync($"/api/Upload/", formData2);

            var fileAfterUpload2 = await IntegrationTestHelper.GetResponseContent <FileListDto>(uploadResponse2);

            listAttachFiles = new List <AttachFileModel>();
            listAttachFiles.Add(new AttachFileModel()
            {
                FileName        = fileAfterUpload2.Files[0].FileName,
                FileStorageName = fileAfterUpload2.Files[0].FileStorageName,
                BlobStorageUrl  = fileAfterUpload2.Files[0].BlobStorageUrl,
                FileSize        = fileAfterUpload2.Files[0].FileSize,
                ThumbnailImage  = fileAfterUpload2.Files[0].ThumbnailImage,
                LocalUrl        = fileAfterUpload2.Files[0].LocalUrl
            });

            UpdateTaskItemCommand command2 = new UpdateTaskItemCommand()
            {
                Name        = "Task With AttachFiles",
                Description = "Description Test",
                TeamId      = Guid.Parse(taskId),
                AttachFiles = listAttachFiles,
                Assignee    = new UserModel()
                {
                    UserId = Guid.NewGuid(), DisplayName = Guid.NewGuid().ToString()
                },
                Deadline  = DateTime.UtcNow,
                Id        = new Guid(taskId),
                Status    = '2',
                Tags      = new List <TagModel>(),
                Relations = new List <RelatedObjectModel>()
            };

            var content2 = IntegrationTestHelper.GetRequestContent(command2);

            var response2 = await client.PutAsync($"/api/TaskItems/Update/{taskId}", content2);

            response2.EnsureSuccessStatusCode();

            // release DB
            _factory.DisposeDbForTests(context);
        }
Beispiel #28
0
 public void NewTestScriptSimplePasses()
 {
     IntegrationTestHelper.WriteToLog();
 }
 public void SetUp()
 {
     _testHelper = new IntegrationTestHelper();
 }
Beispiel #30
0
 public void Setup()
 {
     _rootContainer       = IntegrationTestHelper.SetUp().Build();
     _messageQueueService = _rootContainer.Resolve <IMessageQueueService>();
 }