Наследование: MonoBehaviour
Пример #1
0
        public void Apply_DadoFiltroSemSkip_DeveRetornar0()
        {
            var skip = new Skip();

            var actual = skip.Apply(_filterStub.Object);

            actual.Should().Be(0);
        }
Пример #2
0
        public void Apply_DadoFiltroComSkip_DeveRetornar(int skipValue, int expected)
        {
            _filterStub
                .Setup(p => p.Skip.Value)
                .Returns(skipValue);

            var skip = new Skip();

            var actual = skip.Apply(_filterStub.Object);

            actual.Should().Be(expected);
        }
Пример #3
0
        private static Task CancellationTokenTest(RelationalStorageForTesting sut, TimeSpan timeoutLimit)
        {
            Skip.If(sut == null, "Database was not initialized correctly");
            using (var tokenSource = new CancellationTokenSource(timeoutLimit))
            {
                try
                {
                    //Here one second is added to the task timeout limit in order to account for the delays.
                    //The delays are mainly in the underlying ADO.NET libraries and database.
                    var task = sut.Storage.ReadAsync <int>(sut.CancellationTestQuery, tokenSource.Token);
                    if (!task.Wait(timeoutLimit.Add(TimeSpan.FromSeconds(1))))
                    {
                        Assert.True(false, string.Format("Timeout limit {0} ms exceeded.", timeoutLimit.TotalMilliseconds));
                    }
                }
                catch (Exception ex)
                {
                    //There can be a DbException due to the operation being forcefully cancelled...
                    //... Unless this is a test for a provider which does not support for cancellation.
                    //The exception is wrapped into an AggregrateException due to the test arrangement of hard synchronous
                    //wait to force for actual cancellation check and remove "natural timeout" causes.
                    var innerException = ex?.InnerException;
                    if (sut.Storage.SupportsCommandCancellation())
                    {
                        //If the operation is cancelled already before database calls, a OperationCancelledException
                        //will be thrown in any case.
                        Assert.True(innerException is DbException || innerException is OperationCanceledException, $"Unexpected exception: {ex}");
                    }
                    else
                    {
                        Assert.True(innerException is OperationCanceledException, $"Unexpected exception: {ex}");
                    }
                }
            }

            return(Task.CompletedTask);
        }
Пример #4
0
        public async Task QueryDevicesByClausesTest()
        {
            Skip.IfNot(this.credentialsAvailable, "Skipping this test for Travis pull request as credentials are not available");

            var query = JsonConvert.SerializeObject(new object[]
            {
                new
                {
                    Key      = "tags.Floor",
                    Operator = "EQ",
                    Value    = "10F"
                },
                new
                {
                    Key      = "properties.reported.Device.Location.Latitude",
                    Operator = "GE",
                    Value    = "30"
                },
                new
                {
                    Key      = "properties.desired.Config.TelemetryInterval",
                    Operator = "GE",
                    Value    = 3
                }
            });

            var request = new HttpRequest();

            request.SetUriFromString(AssemblyInitialize.Current.WsHostname + $"/v1/devices?query={query}");
            var response = await this.httpClient.GetAsync(request);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var deviceList = JsonConvert.DeserializeObject <DeviceListApiModel>(response.Content);

            Assert.NotNull(deviceList.Items);
        }
        public void CreateSendPortTwoWay()
        {
            Skip.IfNot(BizTalkServerGroup.IsConfigured);

            var visitor = new BindingInfoBuilder();

            // initialize BindingInfoBuilder.ApplicationName
            ((IApplicationBindingVisitor)visitor).VisitApplicationBinding(new TestApplication());
            var binding = visitor.CreateSendPort(new TwoWaySendPort());

            binding.ApplicationName.Should().Be("TestApplication");
            binding.Description.Should().Be("Some Useless Two-Way Test Send Port");
            binding.Filter.Should().BeNull();
            binding.IsDynamic.Should().BeFalse();
            binding.IsStatic.Should().BeTrue();
            binding.IsTwoWay.Should().BeTrue();
            binding.Name.Should().Be(nameof(TwoWaySendPort));
            binding.PrimaryTransport.FromTime.Should().Be(ServiceWindow.None.StartTime);
            binding.PrimaryTransport.Primary.Should().BeTrue();
            binding.PrimaryTransport.RetryCount.Should().Be(RetryPolicy.Default.Count);
            binding.PrimaryTransport.RetryInterval.Should().Be((int)RetryPolicy.Default.Interval.TotalMinutes);
            binding.PrimaryTransport.SendHandler.Name.Should().Be("Send Host Name");
            binding.PrimaryTransport.SendHandler.TransportType.Name.Should().Be("Test Dummy");
            binding.PrimaryTransport.ServiceWindowEnabled.Should().BeFalse();
            binding.PrimaryTransport.ToTime.Should().Be(ServiceWindow.None.StopTime);
            binding.ReceivePipeline.Name.Should().Be(typeof(PassThruReceive).FullName);
            binding.ReceivePipeline.FullyQualifiedName.Should().Be(typeof(PassThruReceive).AssemblyQualifiedName);
            binding.ReceivePipeline.TrackingOption.Should().Be(PipelineTrackingTypes.None);
            binding.ReceivePipeline.Type.Should().Be(PipelineRef.ReceivePipelineRef().Type);
            binding.ReceivePipelineData.Should().NotBeNullOrEmpty();
            binding.SecondaryTransport.Should().BeNull();
            binding.SendPipelineData.Should().BeEmpty();
            binding.TransmitPipeline.Name.Should().Be(typeof(PassThruTransmit).FullName);
            binding.TransmitPipeline.FullyQualifiedName.Should().Be(typeof(PassThruTransmit).AssemblyQualifiedName);
            binding.TransmitPipeline.TrackingOption.Should().Be(PipelineTrackingTypes.None);
            binding.TransmitPipeline.Type.Should().Be(PipelineRef.TransmitPipelineRef().Type);
        }
Пример #6
0
        public async Task Token_CreateDelete()
        {
            Skip.If(string.IsNullOrEmpty(TestHelper.MasterToken));

            var tokenEntry = new TokenEntry
            {
                Description = "API Testing Token",
                SecretID    = "1ED8D9E5-7868-4A0A-AC2F-6F75BEC71830",
                Local       = true
            };

            var newToken = await _client.Token.Create(tokenEntry);

            Assert.NotEqual(TimeSpan.Zero, newToken.RequestTime);
            Assert.NotNull(newToken.Response);
            Assert.False(string.IsNullOrEmpty(newToken.Response.AccessorID));
            Assert.Equal(tokenEntry.Description, newToken.Response.Description);
            Assert.Equal(tokenEntry.SecretID, newToken.Response.SecretID);
            Assert.Equal(tokenEntry.Local, newToken.Response.Local);

            var deleteResponse = await _client.Token.Delete(newToken.Response.AccessorID);

            Assert.True(deleteResponse.Response);
        }
        public void ValidateDoesNotThrow()
        {
            Skip.IfNot(BizTalkServerGroup.IsConfigured);

            var wba = new WcfBasicHttpRelayAdapter.Inbound(
                a => {
                a.Address                        = new("https://biztalk.factory.servicebus.windows.net/batch-queue");
                a.Identity                       = EndpointIdentityFactory.CreateSpnIdentity("spn_name");
                a.MaxConcurrentCalls             = 201;
                a.MaxReceivedMessageSize         = 64512;
                a.MessageEncoding                = WSMessageEncoding.Mtom;
                a.SuspendRequestMessageOnFailure = true;
                a.IncludeExceptionDetailInFaults = true;

                a.StsUri       = new("https://biztalk.factory-sb.accesscontrol.windows.net/");
                a.IssuerName   = "issuer_name";
                a.IssuerSecret = "issuer_secret";

                a.EnableServiceDiscovery = true;
                a.ServiceDisplayName     = "display_name";
            });

            Invoking(() => ((ISupportValidation)wba).Validate()).Should().NotThrow();
        }
        public void GetDeviceListTest()
        {
            Skip.IfNot(this.credentialsAvailable, "Skipping this test for Travis pull request as credentials are not available");

            var deviceId = "testDevice-getdeviceList";
            var device   = this.CreateDeviceIfNotExists(deviceId);

            try
            {
                var request = new HttpRequest();
                request.SetUriFromString(AssemblyInitialize.Current.WsHostname + $"/v1/devices");
                var response = this.httpClient.GetAsync(request).Result;
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                var deviceList = JsonConvert.DeserializeObject <DeviceListApiModel>(response.Content);
                Assert.True(deviceList.Items.Count >= 1);
                Assert.True(deviceList.Items.Any(d => d.Id == deviceId));
            }
            finally
            {
                // clean it up
                this.DeleteDeviceIfExists(deviceId);
            }
        }
Пример #9
0
        public async Task Policy_CreateDelete()
        {
            Skip.If(string.IsNullOrEmpty(TestHelper.MasterToken));

            var policyEntry = new PolicyEntry()
            {
                Name        = "UnitTestPolicy",
                Description = "Policy for API Unit Testing",
                Rules       = "key \"\" { policy = \"deny\" }"
            };

            var newPolicyResult = await _client.Policy.Create(policyEntry);

            Assert.NotNull(newPolicyResult.Response);
            Assert.NotEqual(TimeSpan.Zero, newPolicyResult.RequestTime);
            Assert.False(string.IsNullOrEmpty(newPolicyResult.Response.ID));
            Assert.Equal(policyEntry.Description, newPolicyResult.Response.Description);
            Assert.Equal(policyEntry.Name, newPolicyResult.Response.Name);
            Assert.Equal(policyEntry.Rules, newPolicyResult.Response.Rules);

            var deleteResponse = await _client.Policy.Delete(newPolicyResult.Response.ID);

            Assert.True(deleteResponse.Response);
        }
Пример #10
0
        public void SparqlEndpointWithExtensions()
        {
            Skip.IfNot(TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteSparql), "Test Config marks Remote SPARQL as unavailable, test cannot be run");

            SparqlConnector endpoint = new SparqlConnector(new Uri(TestConfigManager.GetSetting(TestConfigManager.RemoteSparqlQuery)));

            String testQuery = @"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT * WHERE {?s rdfs:label ?label . ?label bif:contains " + "\"London\" } LIMIT 1";

            Console.WriteLine("Testing Sparql Connector with vendor specific extensions in query");
            Console.WriteLine();
            Console.WriteLine(testQuery);

            Assert.Throws <RdfException>(() =>
            {
                var r = endpoint.Query(testQuery);
            });

            endpoint.SkipLocalParsing = true;

            Object results = endpoint.Query(testQuery);

            TestTools.ShowResults(results);
        }
        public void CaptureMessageBodyWillHaveMessageClaimedButSsoApplicationDoesNotExist()
        {
            Skip.IfNot(BizTalkServerGroup.IsConfigured);

            var actualSsoConfigurationReader = SsoConfigurationReader.Instance;

            // setup a mock callback to ensure that, even if the BizTalk.Factory SSO store is deployed, the call will look for an SSO store that does not exist
            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Callback(() => actualSsoConfigurationReader.Read("NONEXISTENT_APPLICATION", nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Returns(Path.GetTempPath());

                var trackingStreamMock = new Mock <TrackingStream>(TextStreamDummy.Create(1024 * 1024))
                {
                    CallBase = true
                };

                Invoking(() => ClaimStore.Instance.SetupMessageBodyCapture(trackingStreamMock.Object, ActivityTrackingModes.Claim, null))
                .Should().Throw <InvalidOperationException>()
                .WithMessage("AffiliateApplication 'NONEXISTENT_APPLICATION' does not exist.");
            }
        }
Пример #12
0
        public async Task CanSendGetProjectTemplatesRequestAsync()
        {
            Skip.If(PsesStdioProcess.RunningInConstainedLanguageMode, "Plaster doesn't work in ConstrainedLanguage mode.");

            GetProjectTemplatesResponse getProjectTemplatesResponse =
                await PsesLanguageClient
                .SendRequest <GetProjectTemplatesRequest>(
                    "powerShell/getProjectTemplates",
                    new GetProjectTemplatesRequest
            {
                IncludeInstalledModules = true
            })
                .Returning <GetProjectTemplatesResponse>(CancellationToken.None);

            Assert.Collection(getProjectTemplatesResponse.Templates.OrderBy(t => t.Title),
                              template1 =>
            {
                Assert.Equal("AddPSScriptAnalyzerSettings", template1.Title);
            },
                              template2 =>
            {
                Assert.Equal("New PowerShell Manifest Module", template2.Title);
            });
        }
        public void Foreign_Key_Metadata_Is_Correct()
        {
            string runSkippableTests = Environment.GetEnvironmentVariable("SCAFFOLDING_RunSkippableTests");

            Skip.If(string.IsNullOrEmpty(runSkippableTests));

            //Arrange
            var productEntity = TestModel.CategoryProductModel.FindEntityType(typeof(Product));
            var modelMetadata = new ModelMetadata(productEntity, typeof(TestDbContext));

            //Act
            var propertyMetadata = modelMetadata.Properties.FirstOrDefault(p => p.PropertyName == nameof(Product.CategoryId));

            //Assert
            Assert.Equal(nameof(Product.CategoryId), propertyMetadata.PropertyName);
            Assert.False(propertyMetadata.IsPrimaryKey);
            Assert.True(propertyMetadata.IsForeignKey);
            Assert.Equal(typeof(int).FullName, propertyMetadata.TypeName);
            Assert.False(propertyMetadata.IsEnum);
            Assert.False(propertyMetadata.IsAutoGenerated);
            Assert.False(propertyMetadata.IsEnumFlags);
            Assert.False(propertyMetadata.IsReadOnly);
            Assert.True(propertyMetadata.Scaffold);
        }
Пример #14
0
        protected override NameValueCollection GetQueryString()
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["q"]            = Query;
            queryString["prerelease"]   = Prerelease.ToString();
            queryString["ignoreFilter"] = IgnoreFilter.ToString();
            queryString["CountOnly"]    = CountOnly.ToString();

            if (Skip.HasValue)
            {
                queryString["Skip"] = Skip.ToString();
            }

            if (Take.HasValue)
            {
                queryString["Take"] = Take.ToString();
            }

            if (IncludeSemVer2)
            {
                queryString["semVerLevel"] = "2.0.0";
            }

            if (!string.IsNullOrWhiteSpace(SortBy))
            {
                queryString["sortBy"] = SortBy;
            }

            if (LuceneQuery.HasValue)
            {
                queryString["luceneQuery"] = LuceneQuery.ToString();
            }

            return(queryString);
        }
Пример #15
0
        public void ComputeSendPortNameTwoWay()
        {
            Skip.IfNot(BizTalkServerGroup.IsConfigured);

            var applicationBindingMock = new Mock <IApplicationBinding <NamingConventionSpy> >();

            applicationBindingMock.Setup(snc => snc.ResolveName()).Returns("SomeApplication");

            var sendPortMock = new Mock <ISendPort <NamingConventionSpy> >();

            sendPortMock.Setup(sp => sp.GetType()).Returns(typeof(StandaloneSendPort));
            sendPortMock.Setup(sp => sp.ApplicationBinding).Returns(applicationBindingMock.Object);
            sendPortMock.Setup(sp => sp.Transport).Returns(new SendPortTransport <NamingConventionSpy>(sendPortMock.Object)
            {
                Adapter = new FileAdapter.Outbound(_ => { })
            });
            sendPortMock.Setup(sp => sp.IsTwoWay).Returns(true);

            var sut = new NamingConventionSpy {
                Party = "SomeParty", Subject = "SomeMessage", MessageFormat = "SomeFormat"
            };

            sut.ComputeSendPortNameSpy(sendPortMock.Object).Should().Be("SomeApplication.SP2.SomeParty.SomeMessage.FILE.SomeFormat");
        }
Пример #16
0
        public void ComputeAggregateNameIsCalledForReceiveLocation()
        {
            Skip.IfNot(BizTalkServerGroup.IsConfigured);

            var applicationBindingMock = new Mock <IApplicationBinding <NamingConventionSpy> >();

            applicationBindingMock.Setup(snc => snc.ResolveName()).Returns("SomeApplication");

            var receivePortMock = new Mock <IReceivePort <NamingConventionSpy> >();

            receivePortMock.Setup(rp => rp.GetType()).Returns(typeof(StandaloneReceivePort));
            receivePortMock.Setup(rp => rp.ApplicationBinding).Returns(applicationBindingMock.Object);
            receivePortMock.Setup(rp => rp.Name).Returns(new NamingConventionSpy {
                Party = "SomeParty"
            });

            var receiveLocationMock = new Mock <IReceiveLocation <NamingConventionSpy> >();

            receiveLocationMock.Setup(rl => rl.GetType()).Returns(typeof(StandaloneReceiveLocation));
            receiveLocationMock.Setup(rl => rl.ReceivePort).Returns(receivePortMock.Object);
            receiveLocationMock.Setup(rl => rl.Transport)
            .Returns(new ReceiveLocationTransport <NamingConventionSpy>(receiveLocationMock.Object)
            {
                Adapter = new FileAdapter.Inbound(_ => { })
            });

            var namingConventionMock = new Mock <NamingConventionSpy>();

            namingConventionMock.Object.Subject       = "SomeMessage";
            namingConventionMock.Object.MessageFormat = "SomeFormat";

            namingConventionMock.Object.ComputeReceiveLocationNameSpy(receiveLocationMock.Object);

            namingConventionMock.Protected().Verify("ComputeAggregateName", Times.Once(), receivePortMock.Object.GetType());
            namingConventionMock.Protected().Verify("ComputeAggregateName", Times.Once(), receiveLocationMock.Object.GetType());
        }
        public void CreateAndGetDevice()
        {
            Skip.IfNot(this.credentialsAvailable, "Credentials not available for Pull Requests");

            // Act
            var inputDevice = new DeviceModelUsedByDeviceSimulation
            {
                Id = "TEST-CreateDevice-" + Guid.NewGuid()
            };
            var request = new HttpRequest();

            request.SetContent(inputDevice);
            request.SetUriFromString(this.hostname + "/v1/devices");
            this.httpClient.PostAsync(request).Wait();
            request = new HttpRequest();
            request.SetUriFromString(this.hostname + "/v1/devices/" + WebUtility.UrlDecode(inputDevice.Id));
            var response = this.httpClient.GetAsync(request).Result;

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var outputDevice = JsonConvert.DeserializeObject <DeviceModelUsedByDeviceSimulation>(response.Content);

            Assert.Equal(inputDevice.Id, outputDevice.Id);
        }
        public async Task Authentication()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.File(logPath, rollingInterval: RollingInterval.Day)
                         .WriteTo.ColoredConsole(LogEventLevel.Verbose)
                         .CreateLogger();

            Skip.If(string.IsNullOrWhiteSpace(API_SECRET));

            var url = BitfinexValues.ApiWebsocketUrl;

            using (var communicator = new BitfinexWebsocketCommunicator(url))
            {
                AuthenticationResponse received = null;
                var receivedEvent = new ManualResetEvent(false);

                using (var client = new BitfinexWebsocketClient(communicator))
                {
                    client.Streams.AuthenticationStream.Subscribe(auth =>
                    {
                        received = auth;
                        receivedEvent.Set();
                    });

                    await communicator.Start();

                    await client.Authenticate(API_KEY, API_SECRET);

                    receivedEvent.WaitOne(TimeSpan.FromSeconds(30));

                    Assert.NotNull(received);
                    Assert.True(received.IsAuthenticated);
                }
            }
        }
Пример #19
0
        public async Task CanSendCompletionAndCompletionResolveRequestAsync()
        {
            Skip.If(IsLinux, "This depends on the help system, which is flaky on Linux.");
            string filePath = NewTestFile("Write-H");

            CompletionList completionItems = await PsesLanguageClient.TextDocument.RequestCompletion(
                new CompletionParams
            {
                TextDocument = new TextDocumentIdentifier
                {
                    Uri = DocumentUri.FromFileSystemPath(filePath)
                },
                Position = new Position(line: 0, character: 7)
            });

            CompletionItem completionItem = Assert.Single(completionItems,
                                                          completionItem1 => completionItem1.Label == "Write-Host");

            CompletionItem updatedCompletionItem = await PsesLanguageClient
                                                   .SendRequest <CompletionItem>("completionItem/resolve", completionItem)
                                                   .Returning <CompletionItem>(CancellationToken.None);

            Assert.Contains("Writes customized output to a host", updatedCompletionItem.Documentation.String);
        }
Пример #20
0
        public void TestMapDefinitionValidation()
        {
            Skip.If(_skip, _skipReason);

            var conn = CreateTestConnection();
            var mdf  = Utility.CreateMapDefinition(conn, "Test");

            mdf.ResourceID = "Library://UnitTests/Test.MapDefinition";

            var context = new ResourceValidationContext(conn);
            var issues  = ResourceValidatorSet.Validate(context, mdf, false);

            Assert.Contains(issues, x => x.StatusCode == ValidationStatusCode.Warning_MapDefinition_MissingCoordinateSystem);

            conn.ResourceService.SetResourceXmlData("Library://UnitTests/Layers/HydrographicPolygons.LayerDefinition", File.OpenRead("TestData/MappingService/UT_HydrographicPolygons.ldf"));

            var layer = mdf.AddLayer(null, "bar", "Library://UnitTests/Layers/HydrographicPolygons.LayerDefinition");

            layer.Group = "foo"; //AddLayer no longer lets us put in bogus group names
            context     = new ResourceValidationContext(conn);
            issues      = ResourceValidatorSet.Validate(context, mdf, false);
            Assert.Contains(issues, x => x.StatusCode == ValidationStatusCode.Error_MapDefinition_LayerWithNonExistentGroup);

            mdf.AddLayer(null, "bar", "Library://UnitTests/Layers/HydrographicPolygons.LayerDefinition");
            context = new ResourceValidationContext(conn);
            issues  = ResourceValidatorSet.Validate(context, mdf, false);
            Assert.Contains(issues, x => x.StatusCode == ValidationStatusCode.Error_MapDefinition_DuplicateLayerName);

            var group = mdf.AddGroup("foo");

            group.Group = "bar";

            context = new ResourceValidationContext(conn);
            issues  = ResourceValidatorSet.Validate(context, mdf, false);
            Assert.Contains(issues, x => x.StatusCode == ValidationStatusCode.Error_MapDefinition_GroupWithNonExistentGroup);
        }
Пример #21
0
 internal override void WriteSql(StringBuilder sqlText)
 {
     base.WriteSql(sqlText);
     if (Where != null)
     {
         Where.WriteSql(sqlText);
     }
     if (GroupBy != null)
     {
         GroupBy.WriteSql(sqlText);
     }
     if (OrderBy != null)
     {
         OrderBy.WriteSql(sqlText);
     }
     if (Skip != null)
     {
         Skip.WriteSql(sqlText);
     }
     if (Limit != null)
     {
         Limit.WriteSql(sqlText);
     }
 }
Пример #22
0
        public async Task TestCreate()
        {
            Skip.IfNot(SupportsCreate, $"The POST {PluralEndpoint()} is not supported by this controller");

            var client = Factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = NeedsAuthForCreate ? await GetAuthHeaderAsync(HttpMethod.Post, PluralEndpoint()) : null;

            var model = Model.Create();
            var view  = Renderer.ToView(model);

            var response = await client.PostAsJsonAsync(PluralEndpoint(), view);

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());

            var returnedView = await response.Content.ReadAsAsync <TView>();

            var returnedModel = Renderer.FromView(returnedView);

            Model.AssertEqual(model, returnedModel, ignoreId: true);

            Assert.Equal(SingularEndpoint(Model.GetId(returnedModel)), response.Headers.Location);
        }
Пример #23
0
        public async Task LanguageServiceCompletesNamespace()
        {
            Skip.If(
                !VersionUtils.IsNetCore,
                "Windows PowerShell return no results from CommandCompletion in the test harness. Since it works in PS7 and works manually when I run the extension, I'm skipping this  test");

            CompletionResults completionResults =
                await this.GetCompletionResults(
                    CompleteNamespace.SourceDetails);

            Assert.NotEmpty(completionResults.Completions);

            Assert.Equal(
                CompleteNamespace.ExpectedCompletion.CompletionText,
                completionResults.Completions[0].CompletionText
                );

            Assert.Equal(
                CompleteNamespace.ExpectedCompletion.CompletionType,
                completionResults.Completions[0].CompletionType
                );

            Assert.NotNull(completionResults.Completions[0].ToolTipText);
        }
Пример #24
0
        public async Task TestModify()
        {
            Skip.IfNot(SupportsModify, $"The PUT {SingularEndpoint("{id}")} is not supported by this controller");

            var id = await FoundId();

            var client = Factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = NeedsAuthForModify ? await GetAuthHeaderAsync(HttpMethod.Put, SingularEndpoint(id)) : null;

            var modificationModel = Model.Create();
            var modification      = Renderer.ToView(modificationModel);

            var response = await client.PutAsJsonAsync(SingularEndpoint(id), modification);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());

            var modified = await response.Content.ReadAsAsync <TView>();

            var modifiedModel = Renderer.FromView(modified);

            Model.AssertEqual(modificationModel, modifiedModel, ignoreId: true);
        }
Пример #25
0
        public void ParsingUriLoaderDBPedia3()
        {
            Skip.IfNot(TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing), "Test Config marks Remote Parsing as unavailable, test cannot be run");

            int defaultTimeout = Options.UriLoaderTimeout;

            try
            {
                Options.HttpDebugging = true;
                SetUriLoaderCaching(false);
                Options.UriLoaderTimeout = 45000;

                Graph g = new Graph();
                UriLoader.Load(g, new Uri("http://dbpedia.org/ontology/wikiPageRedirects"), new RdfXmlParser());
                Assert.False(g.IsEmpty, "Graph should not be empty");
                TestTools.ShowGraph(g);
            }
            finally
            {
                Options.HttpDebugging = false;
                SetUriLoaderCaching(true);
                Options.UriLoaderTimeout = defaultTimeout;
            }
        }
        public async Task CanSendHoverRequestAsync()
        {
            Skip.If(IsLinux, "This depends on the help system, which is flaky on Linux.");
            string filePath = NewTestFile("Write-Host");

            Hover hover = await PsesLanguageClient.TextDocument.RequestHover(
                new HoverParams
            {
                TextDocument = new TextDocumentIdentifier
                {
                    Uri = DocumentUri.FromFileSystemPath(filePath)
                },
                Position = new Position(line: 0, character: 1)
            }).ConfigureAwait(true);

            Assert.True(hover.Contents.HasMarkedStrings);
            Assert.Collection(hover.Contents.MarkedStrings,
                              str1 => Assert.Equal("function Write-Host", str1.Value),
                              str2 =>
            {
                Assert.Equal("markdown", str2.Language);
                Assert.Equal("Writes customized output to a host.", str2.Value);
            });
        }
Пример #27
0
        public void SetsWikiToFalseWhenWikiDoesntExist()
        {
            Skip.If(this.SkipTestsIssue15());

            // issue #13: the GitHub API only returns whether it's *possible* to create a wiki, but not if the repo actually *has* a wiki.

            // This is a test repo without wiki, but with the "wiki" checkbox set:
            string username = "******";
            string reponame = "wiki-doesnt-exist";

            // We always use this repo, but authenticate with the user from the config to avoid hitting rate limits:
            var source = new ConfigSource();

            source.Hoster   = this.ConfigHoster;
            source.Type     = "user";
            source.Name     = username;
            source.AuthName = TestHelper.EnvVar(this.EnvVarPrefix, "Name");
            source.Password = TestHelper.EnvVar(this.EnvVarPrefix, "PW");

            var repoList = sut.GetRepositoryList(source);
            var repo     = repoList.First(r => r.ShortName == reponame);

            Assert.False(repo.HasWiki);
        }
        public void TestIdentityGenerator_IndividualFiles()
        {
            string runSkippableTests = Environment.GetEnvironmentVariable("SCAFFOLDING_RunSkippableTests");

            Skip.If(string.IsNullOrEmpty(runSkippableTests));

            using (var fileProvider = new TemporaryFileProvider())
            {
                new MsBuildProjectSetupHelper().SetupProjectsForIdentityScaffolder(fileProvider, Output);
                TestProjectPath = Path.Combine(fileProvider.Root, "Root");
                var args = new string[]
                {
                    "-p",
                    Path.Combine(TestProjectPath, "Test.csproj"),
                    "-c",
                    Configuration,
                    "identity",
                    "--dbContext",
                    "Test.Data.MyApplicationDbContext",
                    "--files",
                    "Account.Login;Account.Manage.PersonalData"
                };

                Scaffold(args, TestProjectPath);

                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "Login.cshtml")));
                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "Login.cshtml.cs")));

                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "Manage", "PersonalData.cshtml")));
                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "Manage", "PersonalData.cshtml.cs")));

                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "Manage", "_ViewImports.cshtml")));
                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "Account", "_ViewImports.cshtml")));
                Assert.True(File.Exists(Path.Combine(TestProjectPath, "Areas", "Identity", "Pages", "_ViewImports.cshtml")));
            }
        }
        public async Task CanSendGetCommentHelpRequest()
        {
            Skip.If(
                TestsFixture.RunningInConstainedLanguageMode && TestsFixture.IsWindowsPowerShell,
                "Windows PowerShell doesn't trust PSScriptAnalyzer by default so it won't load.");

            string scriptPath = NewTestFile(@"
function CanSendGetCommentHelpRequest {
    param(
        $myParam,
        $myOtherParam,
        $yetAnotherParam
    )

    # Include other problematic code to make sure this still works
    gci
}
");

            CommentHelpRequestResult commentHelpRequestResult =
                await LanguageClient.SendRequest <CommentHelpRequestResult>(
                    "powerShell/getCommentHelp",
                    new CommentHelpRequestParams
            {
                DocumentUri     = new Uri(scriptPath).ToString(),
                BlockComment    = false,
                TriggerPosition = new Position
                {
                    Line      = 0,
                    Character = 0
                }
            });

            Assert.NotEmpty(commentHelpRequestResult.Content);
            Assert.Contains("myParam", commentHelpRequestResult.Content[7]);
        }
Пример #30
0
        public void TestUpdate()
        {
            Skip.IfNot(EnvUtils.IntegrationTestMachine);

            var dataInfo = _repository.Get(1);

            Assert.True(dataInfo.LastModifiedDate.HasValue);
            var lastModified = dataInfo.LastModifiedDate.Value.Ticks;

            dataInfo.Content          = "new content";
            dataInfo.LastModifiedDate = DateTime.Now.AddDays(-1);

            var updated = _repository.Update(dataInfo);

            Assert.True(updated);

            Assert.Equal(1, dataInfo.Id);
            Assert.True(Utilities.IsGuid(dataInfo.Guid));
            Assert.True(dataInfo.LastModifiedDate.HasValue);
            Assert.Null(dataInfo.TypeVarChar100);
            Assert.Null(dataInfo.TypeVarCharDefault);
            Assert.Equal("new content", dataInfo.Content);
            Assert.Equal(0, dataInfo.Num);
            Assert.Equal(0, dataInfo.Currency);
            Assert.False(dataInfo.Date.HasValue);
            Assert.True(dataInfo.Date == null);

            var lastModified2 = dataInfo.LastModifiedDate.Value.Ticks;

            _output.WriteLine(lastModified.ToString());
            _output.WriteLine(lastModified2.ToString());
            Assert.True(lastModified2 > lastModified);

            updated = _repository.Update((TestTableInfo)null);
            Assert.False(updated);
        }
Пример #31
0
        public void TestHoughLine()
        {
            // hough_line changed the way it codes parameter space in 8.7 ... don't
            // test earlier versions
            Skip.IfNot(NetVips.AtLeastLibvips(8, 7), "requires libvips >= 8.7");

            var test = Image.Black(100, 100).DrawLine(new double[] { 100 }, 10, 90, 90, 10);

            foreach (var fmt in Helper.AllFormats)
            {
                var im    = test.Cast(fmt);
                var hough = im.HoughLine();

                var maxPos = hough.MaxPos();
                var x      = maxPos[1];
                var y      = maxPos[2];

                var angle    = Math.Floor(180.0 * x / hough.Width);
                var distance = Math.Floor(test.Height * y / hough.Height);

                Assert.Equal(45, angle);
                Assert.Equal(70, distance);
            }
        }
Пример #32
0
        public async Task AwaitRegKeyChange_CallingThreadDestroyed()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
            using (var test = new RegKeyTest())
            {
                // Start watching and be certain the thread that started watching is destroyed.
                // This simulates a more common case of someone on a threadpool thread watching
                // a key asynchronously and then the .NET Threadpool deciding to reduce the number of threads in the pool.
                Task watchingTask = null;
                var  thread       = new Thread(() =>
                {
                    watchingTask = test.Key.WaitForChangeAsync(cancellationToken: test.FinishedToken);
                });
                thread.Start();
                thread.Join();

                // Verify that the watching task is still watching.
                Task completedTask = await Task.WhenAny(watchingTask, Task.Delay(AsyncDelay));

                Assert.NotSame(watchingTask, completedTask);
                test.CreateSubKey().Dispose();
                await watchingTask;
            }
        }