public void WadlTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string wadlPath = "./Resources/WADLYahoo.xml";
                const string path     = "yahooWadl";
                string       wadlApi  = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string wadlApiContent;
                    using (StreamReader reader = File.OpenText(wadlPath))
                    {
                        wadlApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.WadlXml,
                        Value  = wadlApiContent
                    };

                    var wadlApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        wadlApi,
                        apiCreateOrUpdate);

                    Assert.NotNull(wadlApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, wadlApi);

                    Assert.NotNull(getResponse);
                    Assert.Equal(wadlApi, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("Yahoo News Search", getResponse.DisplayName);
                    Assert.Equal("http://api.search.yahoo.com/NewsSearchService/V1/", getResponse.ServiceUrl);
                    Assert.True(getResponse.IsCurrent);
                    Assert.True(getResponse.Protocols.Contains(Protocol.Https));
                    Assert.Equal("1", getResponse.ApiRevision);

                    ApiExportResult wadlExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, wadlApi, ExportFormat.Wadl);

                    Assert.NotNull(wadlExport);
                    Assert.NotNull(wadlExport.Value.Link);
                    Assert.Equal("wadl-link-json", wadlExport.ExportResultFormat);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, wadlApi, "*");

                    // clean up all tags
                    var listOfTags = testBase.client.Tag.ListByService(
                        testBase.rgName,
                        testBase.serviceName);
                    foreach (var tag in listOfTags)
                    {
                        testBase.client.NamedValue.Delete(
                            testBase.rgName,
                            testBase.serviceName,
                            tag.Name,
                            "*");
                    }
                }
            }
        }
        public void WsdlTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string wsdlPath = "./Resources/Weather.wsdl";
                const string path     = "weatherapi";
                string       wsdlApi  = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string wsdlApiContent;
                    using (StreamReader reader = File.OpenText(wsdlPath))
                    {
                        wsdlApiContent = reader.ReadToEnd();
                    }

                    // Exporting WSDL is only supported for Soap PassThrough APIs (Apis of Type:soap)
                    // Creating one.
                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path         = path,
                        Format       = ContentFormat.Wsdl,
                        Value        = wsdlApiContent,
                        SoapApiType  = SoapApiType.SoapPassThrough, // create Soap Pass through API
                        WsdlSelector = new ApiCreateOrUpdatePropertiesWsdlSelector()
                        {
                            WsdlServiceName  = "Weather",
                            WsdlEndpointName = "WeatherSoap"
                        }
                    };

                    var wsdlApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        wsdlApi,
                        apiCreateOrUpdate);

                    Assert.NotNull(wsdlApiResponse);
                    Assert.Equal(SoapApiType.SoapPassThrough, wsdlApiResponse.ApiType);

                    // get the api to check it was created
                    var apiContract = testBase.client.Api.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        wsdlApi);

                    Assert.NotNull(apiContract);
                    Assert.Equal(wsdlApi, apiContract.Name);
                    Assert.Equal(path, apiContract.Path);
                    Assert.Equal("Weather", apiContract.DisplayName);
                    Assert.Equal("http://wsf.cdyne.com/WeatherWS/Weather.asmx", apiContract.ServiceUrl);
                    Assert.True(apiContract.IsCurrent);
                    Assert.True(apiContract.Protocols.Contains(Protocol.Https));
                    Assert.Equal("1", apiContract.ApiRevision);

                    /* WSDL Export spits our broken Json
                     * ApiExportResult wsdlExport = testBase.client.ApiExport.Get(
                     *  testBase.rgName,
                     *  testBase.serviceName,
                     *  wsdlApi,
                     *  ExportFormat.Wsdl);
                     *
                     * Assert.NotNull(wsdlExport);
                     * Assert.NotNull(wsdlExport.Value.Link);
                     * Assert.Equal("wsdl-link+xml", wsdlExport.ExportResultFormat);
                     */
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        wsdlApi,
                        "*");
                }
            }
        }
Пример #3
0
        private static KeyBundle CreateKeyVaultKeyAccessibleByIdentity(SqlManagementTestContext context,
                                                                       ResourceGroup resourceGroup, ResourceIdentity identity)
        {
            var sqlClient = context.GetClient <SqlManagementClient>();
            var keyVaultManagementClient = context.GetClient <KeyVaultManagementClient>();
            var keyVaultClient           = TestEnvironmentUtilities.GetKeyVaultClient();

            // Prepare vault permissions for the server
            var permissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.WrapKey,
                    KeyPermissions.UnwrapKey,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };

            var aclEntry = new AccessPolicyEntry(identity.TenantId.Value,
                                                 identity.PrincipalId.Value.ToString(), permissions);

            // Prepare vault permissions for the app used in this test
            var appPermissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.Create,
                    KeyPermissions.Delete,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };
            string authObjectId = TestEnvironmentUtilities.GetUserObjectId();
            var    aclEntryUser = new AccessPolicyEntry(identity.TenantId.Value, authObjectId, appPermissions);

            // Create a vault
            var accessPolicy = new List <AccessPolicyEntry>()
            {
                aclEntry, aclEntryUser
            };
            string vaultName     = SqlManagementTestUtilities.GenerateName();
            string vaultLocation = TestEnvironmentUtilities.DefaultLocation;
            var    vault         = keyVaultManagementClient.Vaults.CreateOrUpdate(resourceGroup.Name, vaultName,
                                                                                  new VaultCreateOrUpdateParameters()
            {
                Location   = vaultLocation,
                Properties = new VaultProperties()
                {
                    AccessPolicies   = accessPolicy,
                    TenantId         = identity.TenantId.Value,
                    EnableSoftDelete = true
                }
            });

            // Create a key
            // This can be flaky if attempted immediately after creating the vault. Adding short sleep to improve robustness.
            TestUtilities.Wait(TimeSpan.FromSeconds(3));
            string keyName = SqlManagementTestUtilities.GenerateName();

            return(keyVaultClient.CreateKeyAsync(vault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa,
                                                 keyOps: JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult());
        }
Пример #4
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // create new group with default parameters
                string backendId = TestUtilities.GenerateName("backendid");
                try
                {
                    string backendName  = TestUtilities.GenerateName("backendName");
                    string urlParameter = new UriBuilder("https", backendName, 443).Uri.ToString();

                    var backendCreateParameters = new BackendContract(urlParameter, BackendProtocol.Http);
                    backendCreateParameters.Description = TestUtilities.GenerateName("description");
                    backendCreateParameters.Tls         = new BackendTlsProperties(
                        validateCertificateChain: true,
                        validateCertificateName: true);
                    backendCreateParameters.Credentials = new BackendCredentialsContract();
                    backendCreateParameters.Credentials.Authorization = new BackendAuthorizationHeaderCredentials()
                    {
                        Parameter = "opensemame",
                        Scheme    = "basic"
                    };
                    backendCreateParameters.Credentials.Query = new Dictionary <string, IList <string> >();
                    backendCreateParameters.Credentials.Query.Add("sv", new List <string> {
                        "xx", "bb", "cc"
                    });
                    backendCreateParameters.Credentials.Header = new Dictionary <string, IList <string> >();
                    backendCreateParameters.Credentials.Header.Add("x-my-1", new List <string> {
                        "val1", "val2"
                    });

                    var backendResponse = testBase.client.Backend.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        backendCreateParameters);

                    Assert.NotNull(backendResponse);

                    // get to check it was created
                    BackendContract backendContract = await testBase.client.Backend.GetAsync(testBase.rgName, testBase.serviceName, backendId);

                    Assert.NotNull(backendContract);
                    Assert.Equal(backendId, backendContract.Name);
                    Assert.NotNull(backendContract.Description);
                    Assert.NotNull(backendContract.Credentials.Authorization);
                    Assert.NotNull(backendContract.Credentials.Query);
                    Assert.NotNull(backendContract.Credentials.Header);
                    Assert.Equal(BackendProtocol.Http, backendContract.Protocol);
                    Assert.Equal(1, backendContract.Credentials.Query.Keys.Count);
                    Assert.Equal(1, backendContract.Credentials.Header.Keys.Count);
                    Assert.NotNull(backendContract.Credentials.Authorization);
                    Assert.Equal("basic", backendContract.Credentials.Authorization.Scheme);

                    var listBackends = testBase.client.Backend.ListByService(testBase.rgName, testBase.serviceName, null);

                    Assert.NotNull(listBackends);

                    // there should be one user
                    Assert.True(listBackends.Count() >= 1);

                    // get the backend etag
                    var backendTag = await testBase.client.Backend.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId);

                    Assert.NotNull(backendTag);
                    Assert.NotNull(backendTag.ETag);

                    // patch backend
                    string patchedDescription = TestUtilities.GenerateName("patchedDescription");
                    testBase.client.Backend.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        new BackendUpdateParameters()
                    {
                        Description = patchedDescription
                    },
                        backendTag.ETag);

                    // get to check it was patched
                    backendContract = await testBase.client.Backend.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId);

                    Assert.NotNull(backendContract);
                    Assert.Equal(backendId, backendContract.Name);
                    Assert.Equal(patchedDescription, backendContract.Description);

                    // get the etag
                    backendTag = await testBase.client.Backend.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId);

                    // delete the backend
                    testBase.client.Backend.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        backendTag.ETag);

                    // get the deleted backend to make sure it was deleted
                    try
                    {
                        testBase.client.Backend.Get(testBase.rgName, testBase.serviceName, backendId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    testBase.client.Backend.Delete(testBase.rgName, testBase.serviceName, backendId, "*");
                }
            }
        }
        public async Task ReturnCocktails_WithHighestAverageRating()
        {
            var cocktailFactoryMock           = new Mock <ICocktailFactory>();
            var cocktailIngredinetFactoryMock = new Mock <ICocktailIngredientFactory>();
            var barCocktailFactoryMock        = new Mock <IBarCocktailFactory>();

            var cocktail1NameTest = "TestName1";
            var cocktail2NameTest = "TestName2";
            var cocktail3NameTest = "TestName3";
            var cocktail4NameTest = "TestName4";


            var CocktailImageUrlTest = "https://www.google.com/";

            var user = new User
            {
                Role = new Role {
                    Name = "user"
                },
                UserName = "******",
                Password = "******"
            };

            var cocktail1 = new Cocktail
            {
                Name      = cocktail1NameTest,
                ImagePath = CocktailImageUrlTest
            };

            var cocktail2 = new Cocktail
            {
                Name      = cocktail2NameTest,
                ImagePath = CocktailImageUrlTest,
            };

            var cocktail3 = new Cocktail
            {
                Name      = cocktail3NameTest,
                ImagePath = CocktailImageUrlTest,
                IsDeleted = true
            };

            var cocktail4 = new Cocktail
            {
                Name      = cocktail4NameTest,
                ImagePath = CocktailImageUrlTest,
            };

            var allRatings = new List <CocktailReview>
            {
                new CocktailReview
                {
                    Cocktail = cocktail1,
                    Rating   = 5,
                    User     = user
                },
                new CocktailReview
                {
                    Cocktail = cocktail1,
                    Rating   = 4,
                    User     = user
                },
                new CocktailReview
                {
                    Cocktail = cocktail2,
                    Rating   = 4,
                    User     = user
                },
                new CocktailReview
                {
                    Cocktail = cocktail3,
                    Rating   = 5,
                    User     = user
                },
                new CocktailReview
                {
                    Cocktail = cocktail4,
                    Rating   = 3,
                    User     = user
                },
            };

            var options = TestUtilities.GetOptions(nameof(ReturnCocktails_WithHighestAverageRating));

            using (var arrangeContext = new CocktailMagicianDb(options))
            {
                arrangeContext.CocktailReviews.AddRange(allRatings);
                await arrangeContext.SaveChangesAsync();
            }

            using (var actContext = new CocktailMagicianDb(options))
            {
                var sut         = new CocktailServices(actContext, cocktailFactoryMock.Object, cocktailIngredinetFactoryMock.Object, barCocktailFactoryMock.Object);
                var mostPopular = await sut.GetMostPopular(2);

                Assert.AreEqual(2, mostPopular.Count());
                Assert.IsFalse(mostPopular.Any(r => r.AverageRating == 3));
                Assert.IsFalse(mostPopular.Any(r => r.AverageRating == 5));
            }
        }
Пример #6
0
        public void Test_LargeSegmentedArchive(
            int minFileSize,
            int minFilesCount,
            int?segmentSize32Bit  = null,
            long?segmentSize64Bit = null)
        {
            if ((segmentSize32Bit.HasValue && segmentSize64Bit.HasValue) ||
                (!segmentSize32Bit.HasValue && !segmentSize64Bit.HasValue))
            {
                Assert.Fail("A single variable, either segmentSize32Bit or segmentSize64Bit has to specified.");
            }

            // There was a claim that large archives (around or above
            // 1gb) did not work well with archive splitting.  This test
            // covers that case.

#if REMOTE_FILESYSTEM
            string parentDir = Path.Combine("t:\\tdir", Path.GetFileNameWithoutExtension(TopLevelDir));
            _FilesToRemove.Add(parentDir);
            Directory.CreateDirectory(parentDir);
            string zipFileToCreate = Path.Combine(parentDir,
                                                  "Create_LargeSegmentedArchive.zip");
#else
            string zipFileToCreate = Path.Combine(TopLevelDir, "Test_LargeSegmentedArchive.zip");
#endif
            TestContext.WriteLine("Creating file {0}", zipFileToCreate);

            // This file will "cache" the randomly generated text, so we
            // don't have to generate more than once. You know, for
            // speed.
            string cacheFile = Path.Combine(TopLevelDir, "cacheFile.txt");

            // int sizeBase =   20 * 1024 * 1024;
            // int sizeRandom = 1 * 1024 * 1024;
            // int numFiles = 3;

            // int sizeBase =   320 * 1024 * 1024;
            // int sizeRandom = 20 * 1024 * 1024 ;
            // int numFiles = 5;

            int sizeRandom = 20 * 1024 * 1024;
            int numFiles   = _rnd.Next(5) + minFilesCount;

            TestContext.WriteLine("The zip will contain {0} files", numFiles);

            int  numSaving = 0, totalToSave = 0, numSegs = 0;
            long sz = 0;


            // There are a bunch of Action<T>'s here.  This test method originally
            // used ZipFile.AddEntry overload that accepts an opener/closer pair.
            // It conjured content for the files out of a RandomTextGenerator
            // stream.  This worked, but was very very slow. So I took a new
            // approach to use a WriteDelegate, and still contrive the data, but
            // cache it for entries after the first one. This makes things go much
            // faster.
            //
            // But, when using the WriteDelegate, the SaveProgress events of
            // flavor ZipProgressEventType.Saving_EntryBytesRead do not get
            // called. Therefore the progress updates are done from within the
            // WriteDelegate itself. The SaveProgress events for SavingStarted,
            // BeforeWriteEntry, and AfterWriteEntry do get called.  As a result
            // this method uses 2 delegates: one for writing and one for the
            // SaveProgress events.

            WriteDelegate writer = (name, stream) =>
            {
                Stream input = null;
                Stream cache = null;
                try
                {
                    // use a cahce file as the content.  The entry
                    // name will vary but we'll get the content for
                    // each entry from the a single cache file.
                    if (File.Exists(cacheFile))
                    {
                        input = File.Open(cacheFile,
                                          FileMode.Open,
                                          FileAccess.ReadWrite,
                                          FileShare.ReadWrite);
                        // Make the file slightly shorter with each
                        // successive entry, - just to shake things
                        // up a little.  Also seek forward a little.
                        var fl = input.Length;
                        input.SetLength(fl - _rnd.Next(sizeRandom / 2) + 5201);
                        input.Seek(_rnd.Next(sizeRandom / 2), SeekOrigin.Begin);
                    }
                    else
                    {
                        sz = minFileSize + _rnd.Next(sizeRandom);
                        // input = new Ionic.Zip.Tests.Utilities.RandomTextInputStream((int)sz);
                        input = new Ionic.Zip.Tests.Utilities.RandomBytesInputStream((int)sz);
                        // cache = File.Create(cacheFile);
                    }
                    _txrx.Send(String.Format("pb 2 max {0}", sz));
                    _txrx.Send("pb 2 value 0");
                    var   buffer = new byte[8192];
                    int   n;
                    Int64 totalWritten = 0;
                    int   nCycles      = 0;
                    using (input)
                    {
                        while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            stream.Write(buffer, 0, n);
                            if (cache != null)
                            {
                                cache.Write(buffer, 0, n);
                            }
                            totalWritten += n;
                            // for performance, don't update the
                            // progress monitor every time.
                            nCycles++;
                            if (nCycles % 312 == 0)
                            {
                                _txrx.Send(String.Format("pb 2 value {0}", totalWritten));
                                _txrx.Send(String.Format("status Saving entry {0}/{1} {2} :: {3}/{4}mb {5:N0}%",
                                                         numSaving, totalToSave,
                                                         name,
                                                         totalWritten / (1024 * 1024), sz / (1024 * 1024),
                                                         ((double)totalWritten) / (0.01 * sz)));
                            }
                        }
                    }
                }
                finally
                {
                    if (cache != null)
                    {
                        cache.Dispose();
                    }
                }
            };

            EventHandler <SaveProgressEventArgs> sp = (sender1, e1) =>
            {
                switch (e1.EventType)
                {
                case ZipProgressEventType.Saving_Started:
                    numSaving = 0;
                    break;

                case ZipProgressEventType.Saving_BeforeWriteEntry:
                    _txrx.Send("test Large Segmented Zip");
                    _txrx.Send(String.Format("status saving {0}", e1.CurrentEntry.FileName));
                    totalToSave = e1.EntriesTotal;
                    numSaving++;
                    break;

                // case ZipProgressEventType.Saving_EntryBytesRead:
                // if (!_pb2Set)
                // {
                //     _txrx.Send(String.Format("pb 2 max {0}", e1.TotalBytesToTransfer));
                //     _pb2Set = true;
                // }
                // _txrx.Send(String.Format("status Saving entry {0}/{1} {2} :: {3}/{4}mb {5:N0}%",
                //                          numSaving, totalToSave,
                //                          e1.CurrentEntry.FileName,
                //                          e1.BytesTransferred/(1024*1024), e1.TotalBytesToTransfer/(1024*1024),
                //                          ((double)e1.BytesTransferred) / (0.01 * e1.TotalBytesToTransfer)));
                // string msg = String.Format("pb 2 value {0}", e1.BytesTransferred);
                // _txrx.Send(msg);
                // break;

                case ZipProgressEventType.Saving_AfterWriteEntry:
                    TestContext.WriteLine("Saved entry {0}, {1} bytes", e1.CurrentEntry.FileName,
                                          e1.CurrentEntry.UncompressedSize);
                    _txrx.Send("pb 1 step");
                    _pb2Set = false;
                    break;
                }
            };

            _txrx = TestUtilities.StartProgressMonitor("largesegmentedzip", "Large Segmented ZIP", "Creating files");

            _txrx.Send("bars 3");
            _txrx.Send("pb 0 max 2");
            _txrx.Send(String.Format("pb 1 max {0}", numFiles));

            // build a large zip file out of thin air
            var sw = new StringWriter();
            using (ZipFile zip = new ZipFile())
            {
                zip.StatusMessageTextWriter = sw;
                zip.BufferSize      = 256 * 1024;
                zip.CodecBufferSize = 128 * 1024;
                if (segmentSize32Bit.HasValue)
                {
                    zip.MaxOutputSegmentSize = segmentSize32Bit.Value;
                }
                else
                {
                    zip.MaxOutputSegmentSize64 = segmentSize64Bit.Value;
                }

                zip.SaveProgress += sp;

                for (int i = 0; i < numFiles; i++)
                {
                    string filename = TestUtilities.GetOneRandomUppercaseAsciiChar() +
                                      Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".txt";
                    zip.AddEntry(filename, writer);
                }
                zip.Save(zipFileToCreate);

                numSegs = zip.NumberOfSegmentsForMostRecentSave;
            }

#if REMOTE_FILESYSTEM
            if (((long)numSegs * zip.MaxOutputSegmentSize64) < (long)(1024 * 1024 * 1024L))
            {
                _FilesToRemove.Remove(parentDir);
                Assert.IsTrue(false, "There were not enough segments in that zip.  numsegs({0}) maxsize({1}).", numSegs, maxSegSize);
            }
#endif
            _txrx.Send("status Verifying the zip ...");

            _txrx.Send("pb 0 step");
            _txrx.Send("pb 1 value 0");
            _txrx.Send("pb 2 value 0");

            ReadOptions options = new ReadOptions
            {
                StatusMessageWriter = new StringWriter()
            };

            string extractDir = "verify";
            int    c          = 0;
            while (Directory.Exists(extractDir + c))
            {
                c++;
            }
            extractDir += c;

            using (ZipFile zip2 = ZipFile.Read(zipFileToCreate, options))
            {
                _numFilesToExtract    = zip2.Entries.Count;
                _numExtracted         = 1;
                _pb1Set               = false;
                zip2.ExtractProgress += ExtractProgress;
                zip2.ExtractAll(extractDir);
            }

            string status = options.StatusMessageWriter.ToString();
            TestContext.WriteLine("status:");
            foreach (string line in status.Split('\n'))
            {
                TestContext.WriteLine(line);
            }
        }
Пример #7
0
 /// <summary>
 /// Executes the specified test method in its own process, offering maximum isolation from ambient noise from other threads
 /// and GC.
 /// </summary>
 /// <param name="testMethodName">The name of the test method.</param>
 /// <returns>
 /// A task whose result is <c>true</c> if test execution is already isolated and should therefore proceed with the body of the test,
 /// or <c>false</c> after the isolated instance of the test has completed execution.
 /// </returns>
 /// <exception cref="Xunit.Sdk.XunitException">Thrown if the isolated test result is a Failure.</exception>
 /// <exception cref="SkipException">Thrown if on a platform that we do not yet support test isolation on.</exception>
 protected Task <bool> ExecuteInIsolationAsync([CallerMemberName] string testMethodName = null !)
 {
     return(TestUtilities.ExecuteInIsolationAsync(this, testMethodName, this.Logger));
 }
        public void CreateAndListCommitmentPlans()
        {
            this.RunAMLCommitmentPlanTestScenario((commitmentPlanName, resourceGroupName, resourcesClient, amlPlansClient) =>
            {
                string plan1Name = TestUtilities.GenerateName(CommitmentPlanTests.TestPlanNamePrefix);
                string plan2Name = TestUtilities.GenerateName(CommitmentPlanTests.TestPlanNamePrefix);
                string plan3Name = TestUtilities.GenerateName(CommitmentPlanTests.TestPlanNamePrefix);

                string resourceGroup1Name = TestUtilities.GenerateName(CommitmentPlanTests.TestResourceGroupNamePrefix);
                string resourceGroup2Name = TestUtilities.GenerateName(CommitmentPlanTests.TestResourceGroupNamePrefix);

                try
                {
                    ResourceSku sku = new ResourceSku(1, CommitmentPlanTests.TestSkuName, CommitmentPlanTests.TestSkuTier);
                    CommitmentPlan inputCommitmentPlan = new CommitmentPlan(CommitmentPlanTests.DefaultLocation, sku: sku);

                    // Create two commitment plans in the first resource group
                    resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroup1Name, new ResourceGroup {
                        Location = CommitmentPlanTests.DefaultLocation
                    });

                    CommitmentPlan outputCommitmentPlan1 = amlPlansClient.CommitmentPlans.CreateOrUpdateWithHttpMessagesAsync(inputCommitmentPlan, resourceGroup1Name, plan1Name).Result.Body;
                    CommitmentPlanTests.ValidateCommitmentPlanResource(amlPlansClient.SubscriptionId, resourceGroup1Name, plan1Name, outputCommitmentPlan1);

                    CommitmentPlan outputCommitmentPlan2 = amlPlansClient.CommitmentPlans.CreateOrUpdateWithHttpMessagesAsync(inputCommitmentPlan, resourceGroup1Name, plan2Name).Result.Body;
                    CommitmentPlanTests.ValidateCommitmentPlanResource(amlPlansClient.SubscriptionId, resourceGroup1Name, plan2Name, outputCommitmentPlan2);

                    // Create one commitment plan in the second resource group
                    resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroup2Name, new ResourceGroup {
                        Location = CommitmentPlanTests.DefaultLocation
                    });

                    CommitmentPlan outputCommitmentPlan3 = amlPlansClient.CommitmentPlans.CreateOrUpdateWithHttpMessagesAsync(inputCommitmentPlan, resourceGroup2Name, plan3Name).Result.Body;
                    CommitmentPlanTests.ValidateCommitmentPlanResource(amlPlansClient.SubscriptionId, resourceGroup2Name, plan3Name, outputCommitmentPlan3);

                    // Get plans from first resource group and validate
                    var plansInGroup1 = amlPlansClient.CommitmentPlans.ListInResourceGroup(resourceGroup1Name);

                    Assert.NotNull(plansInGroup1);
                    Assert.Equal(2, plansInGroup1.Count());

                    string expectedResourceId1 = string.Format(CultureInfo.InvariantCulture, CommitmentPlanTests.ResourceIdFormat, amlPlansClient.SubscriptionId, resourceGroup1Name, plan1Name);
                    Assert.Contains(plansInGroup1, plan => string.Equals(plan.Id, expectedResourceId1, StringComparison.OrdinalIgnoreCase));

                    string expectedResourceId2 = string.Format(CultureInfo.InvariantCulture, CommitmentPlanTests.ResourceIdFormat, amlPlansClient.SubscriptionId, resourceGroup1Name, plan2Name);
                    Assert.Contains(plansInGroup1, plan => string.Equals(plan.Id, expectedResourceId2, StringComparison.OrdinalIgnoreCase));

                    // Get plans from second resource group and validate
                    var plansInGroup2 = amlPlansClient.CommitmentPlans.ListInResourceGroup(resourceGroup2Name);

                    Assert.NotNull(plansInGroup2);
                    Assert.Single(plansInGroup2);

                    string expectedResourceId3 = string.Format(CultureInfo.InvariantCulture, CommitmentPlanTests.ResourceIdFormat, amlPlansClient.SubscriptionId, resourceGroup2Name, plan3Name);
                    Assert.Contains(plansInGroup2, plan => string.Equals(plan.Id, expectedResourceId3, StringComparison.OrdinalIgnoreCase));
                }
                finally
                {
                    // Delete plans and resource groups
                    BaseScenarioTests.DisposeOfTestResource(() => amlPlansClient.CommitmentPlans.RemoveWithHttpMessagesAsync(resourceGroup1Name, plan1Name));
                    BaseScenarioTests.DisposeOfTestResource(() => amlPlansClient.CommitmentPlans.RemoveWithHttpMessagesAsync(resourceGroup1Name, plan2Name));
                    BaseScenarioTests.DisposeOfTestResource(() => resourcesClient.ResourceGroups.Delete(resourceGroup1Name));

                    BaseScenarioTests.DisposeOfTestResource(() => amlPlansClient.CommitmentPlans.RemoveWithHttpMessagesAsync(resourceGroup2Name, plan3Name));
                    BaseScenarioTests.DisposeOfTestResource(() => resourcesClient.ResourceGroups.Delete(resourceGroup2Name));
                }
            });
        }
Пример #9
0
 public void TestInitialize()
 {
     TestUtilities.Initialize();
 }
Пример #10
0
        public void Test_ExportToXml()
        {
            TestUser user = new TestUser();

            user.ID        = Guid.NewGuid();
            user.FirstName = "Test";
            user.LastName  = "Test";

            DataAccess.Data.Saver.Save(user);

            TestRole role = new TestRole();

            role.ID   = Guid.NewGuid();
            role.Name = "Test Role";

            DataAccess.Data.Saver.Save(role);

            TestArticle article = new TestArticle();

            article.ID    = Guid.NewGuid();
            article.Title = "Test";

            DataAccess.Data.Saver.Save(article);

            TestCategory category = new TestCategory();

            category.Name = "Test";

            DataAccess.Data.Saver.Save(category);

            string outputDirectory = TestUtilities.GetTestingPath(this) + Path.DirectorySeparatorChar + "Exported";

            int expectedCount = 0;

            foreach (string dataStoreName in DataAccess.Data.GetDataStoreNames())
            {
                foreach (IEntity entity in DataAccess.Data.Stores[dataStoreName].Indexer.GetEntities())
                {
                    expectedCount++;
                }
            }

            DataExporter exporter = (DataExporter)DataAccess.Data.InitializeDataExporter();

            exporter.ExportDirectoryPath = outputDirectory;

            exporter.ExportToXml();

            Assert.IsTrue(Directory.Exists(outputDirectory), "The output directory doesn't exist.");

            int fileCount = 0;

            foreach (string directory in Directory.GetDirectories(outputDirectory))
            {
                foreach (String file in Directory.GetFiles(directory))
                {
                    fileCount++;
                }
            }

            Assert.AreEqual(expectedCount, fileCount, "Incorrect number of files found.");
        }
Пример #11
0
 public void CleanupTests()
 {
     TestUtilities.EditorTearDownScenes();
 }
Пример #12
0
        static unsafe int Main(string[] args)
        {
            short  testResult          = Pass;
            short  testsCount          = 16;
            string methodUnderTestName = nameof(Sse2.ShuffleHigh);



            if (Sse2.IsSupported)
            {
                string[] permuteData = new string[]
                {
                    "0b11100100",         // identity
                    "0b00011011",         // invert
                    "0b00000000",         // broadcast element 0
                    "0b11111111",         // broadcast element 3
                    "0b01010101",         // broadcast element 1
                    "0b10101010",         // broadcast element 2
                    "0b11011000",         // swap middle elements
                    "0b00100111",         // swap external elements
                    "0b10110001",         // swap internal with external elements
                    "0b11110000",         // divide everything between external elements
                    "0b10100101",         // divide everything between internal elements
                    "0b00010100",         // pattern (0, 1, 1, 0)
                    "0b10000010",         // pattern (2, 0, 0, 2)
                    "0b11001100",         // pattern (3, 0, 3, 0)
                    "0b01100110",         // pattern (1, 2, 1, 2)
                    "0b10011001"          // pattern (2, 1, 2, 1)
                };

                using (var shortTable = TestTableTuvImmSse2 <short, short, byte> .Create(testsCount))
                    using (var ushortTable = TestTableTuvImmSse2 <ushort, ushort, byte> .Create(testsCount))
                    {
                        // Vector128<short> tests

                        TestUtilities.InitializeWithElementNumberingModuloVectorLength <short>(
                            shortTable.inArray1, 16, (int i, int elNo) =>
                        {
                            return((short)(i % 8));
                        });

                        TestUtilities.InitializeWithConstValue <short>(0, shortTable.inArray2);

                        (Vector128 <short>, Vector128 <short>)valueInt16_0 = shortTable[0];
                        Vector128 <short> resultInt16_0 = Sse2.ShuffleHigh(valueInt16_0.Item1, (byte)0b11100100);
                        shortTable.SetOutArray(resultInt16_0, 0, (byte)0b11100100);

                        (Vector128 <short>, Vector128 <short>)valueInt16_1 = shortTable[1];
                        Vector128 <short> resultInt16_1 = Sse2.ShuffleHigh(valueInt16_1.Item1, (byte)0b00011011);
                        shortTable.SetOutArray(resultInt16_1, 1, (byte)0b00011011);

                        (Vector128 <short>, Vector128 <short>)valueInt16_2 = shortTable[2];
                        Vector128 <short> resultInt16_2 = Sse2.ShuffleHigh(valueInt16_2.Item1, (byte)0b00000000);
                        shortTable.SetOutArray(resultInt16_2, 2, (byte)0b00000000);

                        (Vector128 <short>, Vector128 <short>)valueInt16_3 = shortTable[3];
                        Vector128 <short> resultInt16_3 = Sse2.ShuffleHigh(valueInt16_3.Item1, (byte)0b11111111);
                        shortTable.SetOutArray(resultInt16_3, 3, (byte)0b11111111);

                        (Vector128 <short>, Vector128 <short>)valueInt16_4 = shortTable[4];
                        Vector128 <short> resultInt16_4 = Sse2.ShuffleHigh(valueInt16_4.Item1, (byte)0b01010101);
                        shortTable.SetOutArray(resultInt16_4, 4, (byte)0b01010101);

                        (Vector128 <short>, Vector128 <short>)valueInt16_5 = shortTable[5];
                        Vector128 <short> resultInt16_5 = Sse2.ShuffleHigh(valueInt16_5.Item1, (byte)0b10101010);
                        shortTable.SetOutArray(resultInt16_5, 5, (byte)0b10101010);

                        (Vector128 <short>, Vector128 <short>)valueInt16_6 = shortTable[6];
                        Vector128 <short> resultInt16_6 = Sse2.ShuffleHigh(valueInt16_6.Item1, (byte)0b11011000);
                        shortTable.SetOutArray(resultInt16_6, 6, (byte)0b11011000);

                        (Vector128 <short>, Vector128 <short>)valueInt16_7 = shortTable[7];
                        Vector128 <short> resultInt16_7 = Sse2.ShuffleHigh(valueInt16_7.Item1, (byte)0b00100111);
                        shortTable.SetOutArray(resultInt16_7, 7, (byte)0b00100111);

                        (Vector128 <short>, Vector128 <short>)valueInt16_8 = shortTable[8];
                        Vector128 <short> resultInt16_8 = Sse2.ShuffleHigh(valueInt16_8.Item1, (byte)0b10110001);
                        shortTable.SetOutArray(resultInt16_8, 8, (byte)0b10110001);

                        (Vector128 <short>, Vector128 <short>)valueInt16_9 = shortTable[9];
                        Vector128 <short> resultInt16_9 = Sse2.ShuffleHigh(valueInt16_9.Item1, (byte)0b11110000);
                        shortTable.SetOutArray(resultInt16_9, 9, (byte)0b11110000);

                        (Vector128 <short>, Vector128 <short>)valueInt16_10 = shortTable[10];
                        Vector128 <short> resultInt16_10 = Sse2.ShuffleHigh(valueInt16_10.Item1, (byte)0b10100101);
                        shortTable.SetOutArray(resultInt16_10, 10, (byte)0b10100101);

                        (Vector128 <short>, Vector128 <short>)valueInt16_11 = shortTable[11];
                        Vector128 <short> resultInt16_11 = Sse2.ShuffleHigh(valueInt16_11.Item1, (byte)0b00010100);
                        shortTable.SetOutArray(resultInt16_11, 11, (byte)0b00010100);

                        (Vector128 <short>, Vector128 <short>)valueInt16_12 = shortTable[12];
                        Vector128 <short> resultInt16_12 = Sse2.ShuffleHigh(valueInt16_12.Item1, (byte)0b10000010);
                        shortTable.SetOutArray(resultInt16_12, 12, (byte)0b10000010);

                        (Vector128 <short>, Vector128 <short>)valueInt16_13 = shortTable[13];
                        Vector128 <short> resultInt16_13 = Sse2.ShuffleHigh(valueInt16_13.Item1, (byte)0b11001100);
                        shortTable.SetOutArray(resultInt16_13, 13, (byte)0b11001100);

                        (Vector128 <short>, Vector128 <short>)valueInt16_14 = shortTable[14];
                        Vector128 <short> resultInt16_14 = Sse2.ShuffleHigh(valueInt16_14.Item1, (byte)0b01100110);
                        shortTable.SetOutArray(resultInt16_14, 14, (byte)0b01100110);

                        (Vector128 <short>, Vector128 <short>)valueInt16_15 = shortTable[15];
                        Vector128 <short> resultInt16_15 = Sse2.ShuffleHigh(valueInt16_15.Item1, (byte)0b10011001);
                        shortTable.SetOutArray(resultInt16_15, 15, (byte)0b10011001);


                        // Vector128<ushort> tests

                        TestUtilities.InitializeWithElementNumberingModuloVectorLength <ushort>(
                            ushortTable.inArray1, 16, (int i, int elNo) =>
                        {
                            return((ushort)(i % 8));
                        });

                        TestUtilities.InitializeWithConstValue <ushort>(0, ushortTable.inArray2);


                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_0 = ushortTable[0];
                        Vector128 <ushort> resultUInt16_0 = Sse2.ShuffleHigh(valueUInt16_0.Item1, (byte)0b11100100);
                        ushortTable.SetOutArray(resultUInt16_0, 0, (byte)0b11100100);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_1 = ushortTable[1];
                        Vector128 <ushort> resultUInt16_1 = Sse2.ShuffleHigh(valueUInt16_1.Item1, (byte)0b00011011);
                        ushortTable.SetOutArray(resultUInt16_1, 1, (byte)0b00011011);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_2 = ushortTable[2];
                        Vector128 <ushort> resultUInt16_2 = Sse2.ShuffleHigh(valueUInt16_2.Item1, (byte)0b00000000);
                        ushortTable.SetOutArray(resultUInt16_2, 2, (byte)0b00000000);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_3 = ushortTable[3];
                        Vector128 <ushort> resultUInt16_3 = Sse2.ShuffleHigh(valueUInt16_3.Item1, (byte)0b11111111);
                        ushortTable.SetOutArray(resultUInt16_3, 3, (byte)0b11111111);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_4 = ushortTable[4];
                        Vector128 <ushort> resultUInt16_4 = Sse2.ShuffleHigh(valueUInt16_4.Item1, (byte)0b01010101);
                        ushortTable.SetOutArray(resultUInt16_4, 4, (byte)0b01010101);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_5 = ushortTable[5];
                        Vector128 <ushort> resultUInt16_5 = Sse2.ShuffleHigh(valueUInt16_5.Item1, (byte)0b10101010);
                        ushortTable.SetOutArray(resultUInt16_5, 5, (byte)0b10101010);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_6 = ushortTable[6];
                        Vector128 <ushort> resultUInt16_6 = Sse2.ShuffleHigh(valueUInt16_6.Item1, (byte)0b11011000);
                        ushortTable.SetOutArray(resultUInt16_6, 6, (byte)0b11011000);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_7 = ushortTable[7];
                        Vector128 <ushort> resultUInt16_7 = Sse2.ShuffleHigh(valueUInt16_7.Item1, (byte)0b00100111);
                        ushortTable.SetOutArray(resultUInt16_7, 7, (byte)0b00100111);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_8 = ushortTable[8];
                        Vector128 <ushort> resultUInt16_8 = Sse2.ShuffleHigh(valueUInt16_8.Item1, (byte)0b10110001);
                        ushortTable.SetOutArray(resultUInt16_8, 8, (byte)0b10110001);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_9 = ushortTable[9];
                        Vector128 <ushort> resultUInt16_9 = Sse2.ShuffleHigh(valueUInt16_9.Item1, (byte)0b11110000);
                        ushortTable.SetOutArray(resultUInt16_9, 9, (byte)0b11110000);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_10 = ushortTable[10];
                        Vector128 <ushort> resultUInt16_10 = Sse2.ShuffleHigh(valueUInt16_10.Item1, (byte)0b10100101);
                        ushortTable.SetOutArray(resultUInt16_10, 10, (byte)0b10100101);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_11 = ushortTable[11];
                        Vector128 <ushort> resultUInt16_11 = Sse2.ShuffleHigh(valueUInt16_11.Item1, (byte)0b00010100);
                        ushortTable.SetOutArray(resultUInt16_11, 11, (byte)0b00010100);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_12 = ushortTable[12];
                        Vector128 <ushort> resultUInt16_12 = Sse2.ShuffleHigh(valueUInt16_12.Item1, (byte)0b10000010);
                        ushortTable.SetOutArray(resultUInt16_12, 12, (byte)0b10000010);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_13 = ushortTable[13];
                        Vector128 <ushort> resultUInt16_13 = Sse2.ShuffleHigh(valueUInt16_13.Item1, (byte)0b11001100);
                        ushortTable.SetOutArray(resultUInt16_13, 13, (byte)0b11001100);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_14 = ushortTable[14];
                        Vector128 <ushort> resultUInt16_14 = Sse2.ShuffleHigh(valueUInt16_14.Item1, (byte)0b01100110);
                        ushortTable.SetOutArray(resultUInt16_14, 14, (byte)0b01100110);

                        (Vector128 <ushort>, Vector128 <ushort>)valueUInt16_15 = ushortTable[15];
                        Vector128 <ushort> resultUInt16_15 = Sse2.ShuffleHigh(valueUInt16_15.Item1, (byte)0b10011001);
                        ushortTable.SetOutArray(resultUInt16_15, 15, (byte)0b10011001);


                        CheckMethodFive <short, short, byte> checkInt16 = (Span <short> x, byte imm, Span <short> z, Span <short> a) =>
                        {
                            bool result     = true;
                            int  halfLength = x.Length / 2;
                            for (int i = 0; i < x.Length; i++)
                            {
                                if (i < halfLength)
                                {
                                    a[i] = x[i];
                                }
                                else
                                {
                                    a[i] = x[(imm & 0x03) + 4];
                                    imm  = (byte)(imm >> 2);
                                }

                                if (z[i] != a[i])
                                {
                                    result = false;
                                }
                            }
                            return(result);
                        };

                        if (!shortTable.CheckResultShuffle(checkInt16))
                        {
                            PrintError8(shortTable, methodUnderTestName, "CheckResultShuffleHigh", checkInt16);
                            testResult = Fail;
                        }

                        CheckMethodFive <ushort, ushort, byte> checkUInt16 = (Span <ushort> x, byte imm, Span <ushort> z, Span <ushort> a) =>
                        {
                            bool result     = true;
                            int  halfLength = x.Length / 2;
                            for (int i = 0; i < x.Length; i++)
                            {
                                if (i < halfLength)
                                {
                                    a[i] = x[i];
                                }
                                else
                                {
                                    a[i] = x[(imm & 0x03) + 4];
                                    imm  = (byte)(imm >> 2);
                                }

                                if (z[i] != a[i])
                                {
                                    result = false;
                                }
                            }
                            return(result);
                        };

                        if (!ushortTable.CheckResultShuffle(checkUInt16))
                        {
                            PrintError8(ushortTable, methodUnderTestName, "CheckResultShuffleHigh", checkUInt16);
                            testResult = Fail;
                        }
                    }
            }
            else
            {
                Console.WriteLine($"Sse2.IsSupported: {Sse2.IsSupported}, skipped tests of {typeof(Sse2)}.{methodUnderTestName}");
            }
            return(testResult);
        }
Пример #13
0
        public void Constructors(JwtHeaderTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.Constructors", theoryData);

            try
            {
                var jwtHeader = new JwtHeader(theoryData.SigningCredentials, theoryData.OutboundAlgorithmMap);
                theoryData.ExpectedException.ProcessNoException();
                if (theoryData.SigningCredentials != null)
                {
                    if (theoryData.OutboundAlgorithmMap != null)
                    {
                        if (theoryData.OutboundAlgorithmMap.TryGetValue(theoryData.SigningCredentials.Algorithm, out string alg))
                        {
                            if (!jwtHeader.Alg.Equals(alg))
                            {
                                context.AddDiff($"!jwtHeader.Alg.Equals(alg), '{jwtHeader.Alg}' : '{alg}', using OutboundAlgorithmMap");
                            }
                        }
                        else
                        {
                            if (jwtHeader.Alg != theoryData.SigningCredentials.Algorithm)
                            {
                                context.AddDiff($"jwtHeader.Alg != theoryData.SigningCredentials.Algorithm, '{jwtHeader.Alg}' : '{alg}'");
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(theoryData.SigningCredentials.Key.KeyId))
                    {
                        if (!string.IsNullOrEmpty(jwtHeader.Kid))
                        {
                            context.AddDiff($"Kid should not be set as SigningCredentials.Key.KeyId is Null or Empty. Kid : '{jwtHeader.Kid}'");
                        }
                    }
                    else if (!theoryData.SigningCredentials.Key.KeyId.Equals(jwtHeader.Kid))
                    {
                        context.AddDiff($"!theoryData.SigningCredentials.Key.KeyId.Equals(jwtHeader.Kid)");
                    }

                    if (theoryData.SigningCredentials is X509SigningCredentials x509SigningCredentials)
                    {
                        var x5t = jwtHeader[JwtHeaderParameterNames.X5t] as string;
                        if (string.IsNullOrEmpty(x5t))
                        {
                            context.AddDiff("!theoryData.SigningCredentials.Key.KeyId.Equals(jwtHeader.Kid)");
                        }
                        else if (!x5t.Equals(Base64UrlEncoder.Encode(x509SigningCredentials.Certificate.GetCertHash())))
                        {
                            context.AddDiff("!x5t.Equals(Base64UrlEncoder.Encode(x509SigningCredentials.Certificate.GetCertHash()))");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
        public void OpenApiInJsonTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string openapiFilePath = "./Resources/petstoreOpenApi.json";
                const string path            = "openapi4";
                string       openApiId       = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string openApiContent;
                    using (StreamReader reader = File.OpenText(openapiFilePath))
                    {
                        openApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.Openapijson,
                        Value  = openApiContent
                    };

                    var swaggerApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        openApiId,
                        apiCreateOrUpdate);

                    Assert.NotNull(swaggerApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, openApiId);

                    Assert.NotNull(getResponse);
                    Assert.Equal(openApiId, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("Swagger Petstore", getResponse.DisplayName);
                    Assert.Equal("http://petstore.swagger.io/v2", getResponse.ServiceUrl);

                    ApiExportResult openApiExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, openApiId, ExportFormat.Openapi);

                    Assert.NotNull(openApiExport);
                    Assert.NotNull(openApiExport.Value.Link);
                    Assert.Equal("openapi-link", openApiExport.ExportResultFormat);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, openApiId, "*");

                    // clean up all tags
                    var listOfTags = testBase.client.Tag.ListByService(
                        testBase.rgName,
                        testBase.serviceName);
                    foreach (var tag in listOfTags)
                    {
                        testBase.client.Tag.Delete(
                            testBase.rgName,
                            testBase.serviceName,
                            tag.Name,
                            "*");
                    }
                }
            }
        }
Пример #15
0
 /// <summary>
 /// Executes the specified test method in its own process, offering maximum isolation from ambient noise from other threads
 /// and GC.
 /// </summary>
 /// <param name="testMethodName">The name of the test method.</param>
 /// <returns>
 /// <c>true</c> if test execution is already isolated and should therefore proceed with the body of the test,
 /// or <c>false</c> after the isolated instance of the test has completed execution.
 /// </returns>
 /// <exception cref="Xunit.Sdk.XunitException">Thrown if the isolated test result is a Failure.</exception>
 /// <exception cref="SkipException">Thrown if on a platform that we do not yet support test isolation on.</exception>
 protected bool ExecuteInIsolation([CallerMemberName] string testMethodName = null !)
 {
     return(TestUtilities.ExecuteInIsolationAsync(this, testMethodName, this.Logger).GetAwaiter().GetResult());
 }
        public void OpenApi2ImportsInfoTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string swaggerPath = "./Resources/SwaggerInfoTos.json";
                const string path        = "swaggerApi";
                string       swaggerApi  = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string swaggerApiContent;
                    using (StreamReader reader = File.OpenText(swaggerPath))
                    {
                        swaggerApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.SwaggerJson,
                        Value  = swaggerApiContent
                    };

                    var swaggerApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        swaggerApi,
                        apiCreateOrUpdate);

                    Assert.NotNull(swaggerApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, swaggerApi);

                    Assert.NotNull(getResponse);
                    Assert.Equal(swaggerApi, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("https://contoso.com/tos", getResponse.TermsOfServiceUrl);

                    Assert.Equal("Bob", getResponse.Contact?.Name);
                    Assert.Equal("https://contoso.com/bob", getResponse.Contact?.Url);
                    Assert.Equal("*****@*****.**", getResponse.Contact?.Email);

                    Assert.Equal("Contoso license", getResponse.License?.Name);
                    Assert.Equal("https://contoso.com/license", getResponse.License?.Url);
                    ApiExportResult swaggerExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, swaggerApi, ExportFormat.Swagger);

                    Assert.NotNull(swaggerExport);
                    Assert.NotNull(swaggerExport.Value.Link);
                    Assert.Equal("swagger-link-json", swaggerExport.ExportResultFormat);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, swaggerApi, "*");

                    // clean up all tags
                    var listOfTags = testBase.client.Tag.ListByService(
                        testBase.rgName,
                        testBase.serviceName);
                    foreach (var tag in listOfTags)
                    {
                        testBase.client.Tag.Delete(
                            testBase.rgName,
                            testBase.serviceName,
                            tag.Name,
                            "*");
                    }
                }
            }
        }
Пример #17
0
        public void CanCreateWithDefaultETag()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var region         = Region.USEast;
                var groupName      = TestUtilities.GenerateName("rgdnschash");
                var topLevelDomain = $"{TestUtilities.GenerateName("www.contoso-")}.com";

                var azure = TestHelper.CreateRollupClient();
                try
                {
                    var dnsZone = azure.DnsZones.Define(topLevelDomain)
                                  .WithNewResourceGroup(groupName, region)
                                  .DefineARecordSet("www")
                                  .WithIPv4Address("23.96.104.40")
                                  .WithIPv4Address("24.97.105.41")
                                  .WithTimeToLive(7200)
                                  .WithETagCheck()
                                  .Attach()
                                  .DefineAaaaRecordSet("www")
                                  .WithIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
                                  .WithIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335")
                                  .WithETagCheck()
                                  .Attach()
                                  .DefineCNameRecordSet("documents")
                                  .WithAlias("doc.contoso.com")
                                  .WithETagCheck()
                                  .Attach()
                                  .DefineCNameRecordSet("userguide")
                                  .WithAlias("doc.contoso.com")
                                  .WithETagCheck()
                                  .Attach()
                                  .Create();

                    // Check A records
                    var aRecordSets = dnsZone.ARecordSets.List();
                    Assert.True(aRecordSets.Count() == 1);
                    Assert.True(aRecordSets.ElementAt(0).TimeToLive == 7200);

                    // Check AAAA records
                    var aaaaRecordSets = dnsZone.AaaaRecordSets.List();
                    Assert.Single(aaaaRecordSets);
                    Assert.StartsWith("www", aaaaRecordSets.ElementAt(0).Name);
                    Assert.Equal(2, aaaaRecordSets.ElementAt(0).IPv6Addresses.Count());

                    // Check CNAME records
                    var cnameRecordSets = dnsZone.CNameRecordSets.List();
                    Assert.True(cnameRecordSets.Count() == 2);

                    AggregateException compositeException = null;
                    try
                    {
                        azure.DnsZones.Define(topLevelDomain)
                        .WithNewResourceGroup(groupName, region)
                        .DefineARecordSet("www")
                        .WithIPv4Address("23.96.104.40")
                        .WithIPv4Address("24.97.105.41")
                        .WithTimeToLive(7200)
                        .WithETagCheck()
                        .Attach()
                        .DefineAaaaRecordSet("www")
                        .WithIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
                        .WithIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335")
                        .WithETagCheck()
                        .Attach()
                        .DefineCNameRecordSet("documents")
                        .WithAlias("doc.contoso.com")
                        .WithETagCheck()
                        .Attach()
                        .DefineCNameRecordSet("userguide")
                        .WithAlias("doc.contoso.com")
                        .WithETagCheck()
                        .Attach()
                        .Create();
                    }
                    catch (AggregateException exception)
                    {
                        compositeException = exception;
                    }
                    Assert.NotNull(compositeException);
                    Assert.NotNull(compositeException.InnerExceptions);
                    Assert.Equal(4, compositeException.InnerExceptions.Count);
                    foreach (var exception in compositeException.InnerExceptions)
                    {
                        Assert.True(exception is CloudException);
                        CloudError cloudError = ((CloudException)exception).Body;
                        Assert.NotNull(cloudError);
                        Assert.NotNull(cloudError.Code);
                        Assert.Contains("PreconditionFailed", cloudError.Code);
                    }
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(groupName);
                    }
                    catch
                    { }
                }
            }
        }
        public async Task AllReviewsAsync()
        {
            var userName = "******";
            var userName2 = "user";
            var userpassword = "******";
            var roleId = 1;
            var barTestName = "New Bar";
            var imageUrlTest = "https://www.google.bg/";


            var userServicesMock = new Mock<IUserServices>();
            var barReviewFactoryMock = new Mock<IBarReviewFactory>();

            var addressTest = new Address
            {
                Name = "AddressTest",
                City = new City { Name = "SofiaTest" },
                Latitude = 1.1,
                Longitude = 1.1
            };

            var barTest = new Bar
            {
                Name = barTestName,
                ImagePath = imageUrlTest,
                Address = addressTest,
            };


            var user = new User(userName, userpassword, roleId);
            var user2 = new User(userName2, userpassword, roleId);
            var barReview1 = new BarReview
            {
                Bar = barTest,
                User = user
            };

            var barReview2 = new BarReview
            {
                Bar = barTest,
                User = user2
            };

            userServicesMock
                .Setup(r => r.FindUserAsync(userName))
                .ReturnsAsync(user);

            var options = TestUtilities.GetOptions(nameof(AllReviewsAsync));

            using (var arrangeContext = new CocktailMagicianDb(options))
            {
                arrangeContext.Bars.Add(barTest);
                arrangeContext.Users.Add(user);
                arrangeContext.Users.Add(user2);
                arrangeContext.BarReviews.Add(barReview1);
                arrangeContext.BarReviews.Add(barReview2);
                await arrangeContext.SaveChangesAsync();
            }

            using (var actContext = new CocktailMagicianDb(options))
            {


                var barFound = await actContext.Bars.Where(b => b.Name == barTest.Name).Select(b => b.Id).FirstAsync();
                var sut = new BarReviewServices(barReviewFactoryMock.Object, actContext );
                await sut.AllReviewsAsync(barFound);
            }

            using (var assertContext = new CocktailMagicianDb(options))
            {
                Assert.AreEqual(2, assertContext.BarReviews.Count());
            }
        }
Пример #19
0
        public void CanDeleteWithExplicitETag()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var region         = Region.USEast;
                var groupName      = TestUtilities.GenerateName("rgdnschash");
                var topLevelDomain = $"{TestUtilities.GenerateName("www.contoso-")}.com";

                var azure = TestHelper.CreateRollupClient();
                try
                {
                    var dnsZone = azure.DnsZones.Define(topLevelDomain)
                                  .WithNewResourceGroup(groupName, region)
                                  .DefineARecordSet("www")
                                  .WithIPv4Address("23.96.104.40")
                                  .WithIPv4Address("24.97.105.41")
                                  .WithTimeToLive(7200)
                                  .WithETagCheck()
                                  .Attach()
                                  .DefineAaaaRecordSet("www")
                                  .WithIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
                                  .WithIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335")
                                  .WithETagCheck()
                                  .Attach()
                                  .Create();

                    // Check A records
                    var aRecordSets = dnsZone.ARecordSets.List();
                    Assert.True(aRecordSets.Count() == 1);
                    var aRecordSet = aRecordSets.ElementAt(0);
                    Assert.NotNull(aRecordSet.ETag);

                    // Check AAAA records
                    var aaaaRecordSets = dnsZone.AaaaRecordSets.List();
                    Assert.True(aaaaRecordSets.Count() == 1);
                    var aaaaRecordSet = aaaaRecordSets.ElementAt(0);
                    Assert.NotNull(aaaaRecordSet.ETag);

                    // Try delete with invalid eTag
                    //
                    AggregateException compositeException = null;
                    try
                    {
                        dnsZone.Update()
                        .WithoutARecordSet("www", aRecordSet.ETag + "-foo")
                        .WithoutAaaaRecordSet("www", aaaaRecordSet.ETag + "-foo")
                        .Apply();
                    }
                    catch (AggregateException exception)
                    {
                        compositeException = exception;
                    }
                    Assert.NotNull(compositeException);
                    Assert.Equal(2, compositeException.InnerExceptions.Count());
                    foreach (var exception in compositeException.InnerExceptions)
                    {
                        Assert.True(exception is CloudException);
                        CloudError cloudError = ((CloudException)exception).Body;
                        Assert.NotNull(cloudError);
                        Assert.NotNull(cloudError.Code);
                        Assert.Contains("PreconditionFailed", cloudError.Code);
                    }

                    // Try delete with correct etags
                    dnsZone.Update()
                    .WithoutARecordSet("www", aRecordSet.ETag)
                    .WithoutAaaaRecordSet("www", aaaaRecordSet.ETag)
                    .Apply();

                    // Check A records
                    aRecordSets = dnsZone.ARecordSets.List();
                    Assert.True(aRecordSets.Count() == 0);

                    // Check AAAA records
                    aaaaRecordSets = dnsZone.AaaaRecordSets.List();
                    Assert.True(aaaaRecordSets.Count() == 0);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(groupName);
                    }
                    catch
                    { }
                }
            }
        }
Пример #20
0
        public void CanBringIntoViewElements()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone5))
            {
                Log.Warning("Skipping since version is less than RS5 and effective viewport is not available below RS5");
                return;
            }

            if (!PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone3))
            {
                Log.Warning("Skipping CanBringIntoViewElements because UIElement.BringIntoViewRequested was added in RS4.");
                return;
            }

            ScrollViewer  scroller        = null;
            ItemsRepeater repeater        = null;
            var           rootLoadedEvent = new AutoResetEvent(initialState: false);
            var           effectiveViewChangeCompletedEvent = new AutoResetEvent(initialState: false);
            var           viewChangeCompletedEvent          = new AutoResetEvent(initialState: false);

            var viewChangedOffsets = new List <double>();

            RunOnUIThread.Execute(() =>
            {
                var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus.";
                var root  = (Grid)XamlReader.Load(TestUtilities.ProcessTestXamlForRepo(
                                                      @"<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:controls='using:Microsoft.UI.Xaml.Controls'> 
                         <Grid.Resources>
                           <controls:StackLayout x:Name='VerticalStackLayout' />
                           <controls:RecyclingElementFactory x:Key='ElementFactory'>
                             <controls:RecyclingElementFactory.RecyclePool>
                               <controls:RecyclePool />
                             </controls:RecyclingElementFactory.RecyclePool>
                             <DataTemplate x:Key='ItemTemplate'>
                               <Border Background='LightGray' Margin ='5'>
                                 <TextBlock Text='{Binding}' TextWrapping='WrapWholeWords' />
                               </Border>
                             </DataTemplate>
                           </controls:RecyclingElementFactory>
                         </Grid.Resources>
                         <ScrollViewer x:Name='Scroller' Width='400' Height='600' Background='Gray'>
                           <controls:ItemsRepeater
                             x:Name='ItemsRepeater'
                             ItemTemplate='{StaticResource ElementFactory}'
                             Layout='{StaticResource VerticalStackLayout}'
                             HorizontalCacheLength='0'
                             VerticalCacheLength='0' />
                         </ScrollViewer>
                       </Grid>"));

                var elementFactory = (RecyclingElementFactory)root.Resources["ElementFactory"];
                scroller           = (ScrollViewer)root.FindName("Scroller");
                repeater           = (ItemsRepeater)root.FindName("ItemsRepeater");

                var items = Enumerable.Range(0, 400).Select(i => string.Format("{0}: {1}", i, lorem.Substring(0, 250)));

                repeater.ItemsSource = items;

                scroller.ViewChanged += (o, e) =>
                {
                    Log.Comment("ViewChanged: " + scroller.VerticalOffset);
                    viewChangedOffsets.Add(scroller.VerticalOffset);
                    if (!e.IsIntermediate)
                    {
                        viewChangeCompletedEvent.Set();
                    }
                };

                scroller.EffectiveViewportChanged += (o, args) =>
                {
                    effectiveViewChangeCompletedEvent.Set();
                };

                Content = root;

                root.Loaded += delegate
                {
                    rootLoadedEvent.Set();
                };
            });
            Verify.IsTrue(rootLoadedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                repeater.GetOrCreateElement(100).StartBringIntoView();
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangeCompletedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.AreEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();

            ValidateRealizedRange(repeater, 99, 106);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll into view item 105 (already realized) w/ animation.");
                repeater.TryGetElement(105).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangeCompletedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.IsLessThanOrEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();
            ValidateRealizedRange(repeater, 101, 109);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll item 0 to the top w/ animation and 0.5 vertical alignment.");
                repeater.GetOrCreateElement(0).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangeCompletedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            viewChangedOffsets.Clear();
            ValidateRealizedRange(repeater, 0, 6);

            RunOnUIThread.Execute(() =>
            {
                // You can't align the first group in the middle obviously.
                Verify.AreEqual(0, scroller.VerticalOffset);

                Log.Comment("Scroll to item 20.");
                repeater.GetOrCreateElement(20).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.0
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangeCompletedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            ValidateRealizedRange(repeater, 19, 26);
        }
Пример #21
0
        public async Task ServiceFabricCreateUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // create new group with default parameters
                string backendId     = TestUtilities.GenerateName("sfbackend");
                string certificateId = TestUtilities.GenerateName("certificateId");
                try
                {
                    var base64ArrayCertificate = Convert.FromBase64String(testBase.base64EncodedTestCertificateData);
                    var cert = new X509Certificate2(base64ArrayCertificate, testBase.testCertificatePassword);

                    var createResponse = testBase.client.Certificate.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        certificateId,
                        new CertificateCreateOrUpdateParameters
                    {
                        Data     = testBase.base64EncodedTestCertificateData,
                        Password = testBase.testCertificatePassword
                    },
                        null);

                    Assert.NotNull(createResponse);
                    Assert.Equal(certificateId, createResponse.Name);

                    string backendName      = TestUtilities.GenerateName("backendName");
                    string urlParameter     = new UriBuilder("https", backendName, 443).Uri.ToString();
                    string servicefabricUrl = "fabric:/mytestapp/mytestservice";

                    var backendCreateParameters = new BackendContract(servicefabricUrl, BackendProtocol.Http);
                    backendCreateParameters.Description = TestUtilities.GenerateName("description");
                    backendCreateParameters.Properties  = new BackendProperties();
                    backendCreateParameters.Properties.ServiceFabricCluster = new BackendServiceFabricClusterProperties();
                    backendCreateParameters.Properties.ServiceFabricCluster.ClientCertificateId = $"/subscriptions/{testBase.subscriptionId}/resourceGroups/{testBase.rgName}/providers/Microsoft.ApiManagement/service/{testBase.serviceName}/certificates/{certificateId}";
                    backendCreateParameters.Properties.ServiceFabricCluster.ManagementEndpoints = new List <string>();
                    backendCreateParameters.Properties.ServiceFabricCluster.ManagementEndpoints.Add(urlParameter);
                    backendCreateParameters.Properties.ServiceFabricCluster.MaxPartitionResolutionRetries = 5;
                    backendCreateParameters.Properties.ServiceFabricCluster.ServerX509Names = new List <X509CertificateName>();
                    backendCreateParameters.Properties.ServiceFabricCluster.ServerX509Names.Add(new X509CertificateName("serverCommonName1", cert.Thumbprint));

                    var backendContract = testBase.client.Backend.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        backendCreateParameters);

                    Assert.NotNull(backendContract);
                    Assert.Equal(backendId, backendContract.Name);
                    Assert.NotNull(backendContract.Description);
                    Assert.NotNull(backendContract.Properties.ServiceFabricCluster);
                    Assert.Equal(BackendProtocol.Http, backendContract.Protocol);
                    Assert.Equal(1, backendContract.Properties.ServiceFabricCluster.ServerX509Names.Count);
                    Assert.Equal(1, backendContract.Properties.ServiceFabricCluster.ManagementEndpoints.Count);
                    Assert.Equal(5, backendContract.Properties.ServiceFabricCluster.MaxPartitionResolutionRetries);

                    var listBackends = testBase.client.Backend.ListByService(testBase.rgName, testBase.serviceName, null);

                    Assert.NotNull(listBackends);

                    // there should be atleast one backend
                    Assert.True(listBackends.Count() >= 1);

                    // reconnect backend
                    var backendReconnectParams = new BackendReconnectContract()
                    {
                        After = TimeSpan.FromMinutes(5d)
                    };

                    await testBase.client.Backend.ReconnectAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        backendReconnectParams);

                    // patch backend
                    string patchedDescription = TestUtilities.GenerateName("patchedDescription");
                    testBase.client.Backend.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        new BackendUpdateParameters()
                    {
                        Description = patchedDescription
                    },
                        "*");

                    // get to check it was patched
                    backendContract = await testBase.client.Backend.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId);

                    Assert.NotNull(backendContract);
                    Assert.Equal(backendId, backendContract.Name);
                    Assert.Equal(patchedDescription, backendContract.Description);

                    // get the etag
                    var backendTag = await testBase.client.Backend.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId);

                    Assert.NotNull(backendTag);
                    Assert.NotNull(backendTag.ETag);

                    // delete the backend
                    testBase.client.Backend.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        backendId,
                        backendTag.ETag);

                    // get the deleted backend to make sure it was deleted
                    try
                    {
                        testBase.client.Backend.Get(testBase.rgName, testBase.serviceName, backendId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    testBase.client.Backend.Delete(testBase.rgName, testBase.serviceName, backendId, "*");
                    testBase.client.Certificate.Delete(testBase.rgName, testBase.serviceName, certificateId, "*");
                }
            }
        }
Пример #22
0
        /// <summary>
        ///   Finds or creates and fills a cache directory of fodder files.
        /// </summary>
        /// <returns>the name of the cache directory</returns>
        String CreateSomeFiles()
        {
            string fodderName = "fodder";

            if (_fodderDir != null)
            {
                CreateSymbolicLink(fodderName, _fodderDir, 1);
                return(fodderName);
            }

            int    baseNumFiles  = 12;
            int    baseSize      = 0x100000;
            int    numFilesToAdd = baseNumFiles + _rnd.Next(4);
            string tmpDir        = System.Environment.GetEnvironmentVariable("TEMP");
            var    oldDirs       = Directory.GetDirectories(tmpDir, "*.SplitArchives");
            string fodderDir;

            foreach (var dir in oldDirs)
            {
                TestContext.WriteLine("Considering directory: {0}", dir);
                fodderDir = Path.Combine(dir, fodderName);
                if (!Directory.Exists(fodderDir))
                {
                    Directory.Delete(dir, true);
                }
                else
                {
                    var fodderFiles = Directory.GetFiles(fodderDir, "*.txt");
                    if (fodderFiles.Length < baseNumFiles)
                    {
                        Directory.Delete(dir, true);
                    }
                    else
                    {
                        _fodderDir = fodderDir;
                        CreateSymbolicLink(fodderName, _fodderDir, 1);
                        return(fodderName);
                    }
                }
            }

            // upon reaching here, no directories exist that contain suitable
            // fodder for these tests.  Create the directory, and a few
            // fodder files.

            string pname = Path.GetFileName(TestUtilities.GenerateUniquePathname("SplitArchives"));

            string cacheDir = Path.Combine(tmpDir, pname);

            Directory.CreateDirectory(cacheDir);
            fodderDir = Path.Combine(cacheDir, fodderName);
            Directory.CreateDirectory(fodderDir);

            for (int i = 0; i < numFilesToAdd; i++)
            {
                int    fileSize = baseSize + _rnd.Next(baseSize / 2);
                string fileName = Path.Combine(fodderDir, string.Format("Pippo{0}.txt", i));
                TestUtilities.CreateAndFillFileText(fileName, fileSize);
            }
            _fodderDir = fodderDir;
            CreateSymbolicLink(fodderName, _fodderDir, 1);
            return(fodderName);
        }
        public void CompanionGameObject_ActivatesIfNotPrefabOrDisabled()
        {
            // Create a prefab asset with an Hybrid Component
            var prefab     = CreateGameObject("prefab", typeof(ConversionTestHybridComponent));
            var prefabPath = m_TempAssetDir + "/TestPrefab.prefab";

            Assert.IsFalse(prefab.IsPrefab());
            prefab = PrefabUtility.SaveAsPrefabAsset(prefab, prefabPath, out var success);
            Assert.IsTrue(success && prefab.IsPrefab());

            // Create a GameObject that references the prefab, in order to trigger the conversion of the prefab
            var gameObject = CreateGameObject("prefab_ref", typeof(ConversionTestHybridComponentPrefabReference));

            gameObject.GetComponent <ConversionTestHybridComponentPrefabReference>().Prefab = prefab;

            // Run the actual conversion, we only care about the prefab so we destroy the other entity
            var settings = MakeDefaultSettings().WithExtraSystem <MonoBehaviourComponentConversionSystem>();
            var dummy    = GameObjectConversionUtility.ConvertGameObjectHierarchy(gameObject, settings);

            m_Manager.DestroyEntity(dummy);
            EntitiesAssert.ContainsOnly(m_Manager, EntityMatch.Exact <CompanionLink, ConversionTestHybridComponent, Prefab, LinkedEntityGroup>(k_CommonComponents));

            // Accessing the prefab entity and its companion GameObject can't be directly done with GetSingleton because it requires EntityQueryOptions.IncludePrefab
            var companionQuery = EmptySystem.GetEntityQuery(new EntityQueryDesc
            {
                All     = new[] { ComponentType.ReadOnly <CompanionLink>() },
                Options = EntityQueryOptions.IncludePrefab
            });
            var prefabEntity    = companionQuery.GetSingletonEntity();
            var prefabCompanion = m_Manager.GetComponentData <CompanionLink>(prefabEntity).Companion;

            // Create an instance, the expectation is that the prefab remains inactive, but the instance activates
            var instanceEntity    = m_Manager.Instantiate(prefabEntity);
            var instanceCompanion = m_Manager.GetComponentData <CompanionLink>(instanceEntity).Companion;

            // Activation happens through a system, so before the first update everything is inactive
            Assert.IsFalse(prefabCompanion.activeSelf);
            Assert.IsFalse(instanceCompanion.activeSelf);

            // Register all the Hybrid Component related systems, including the one that deals with activation
            TestUtilities.RegisterSystems(World, TestUtilities.SystemCategories.HybridComponents);

            // After an update, the prefab should remain inactive, but the instance should be active
            World.Update();
            Assert.IsFalse(prefabCompanion.activeSelf);
            Assert.IsTrue(instanceCompanion.activeSelf);

            // Let's reverse the test, demote the prefab to a regular entity, and disable the instance
            m_Manager.RemoveComponent <Prefab>(prefabEntity);
            m_Manager.AddComponent <Disabled>(instanceEntity);

            // After an update, the prefab which isn't one anymore should be active, and the disabled entity should be inactive
            World.Update();
            Assert.IsTrue(prefabCompanion.activeSelf);
            Assert.IsFalse(instanceCompanion.activeSelf);

            // Let's reverse once more and get back to the initial state
            m_Manager.AddComponent <Prefab>(prefabEntity);
            m_Manager.RemoveComponent <Disabled>(instanceEntity);

            // After an update, the prefab should be inactive again, and the instance should be active again
            World.Update();
            Assert.IsFalse(prefabCompanion.activeSelf);
            Assert.IsTrue(instanceCompanion.activeSelf);
        }