public TestBuilder CreateTest(GlobalSetupManager globalSetupManager, TestBuilder parentTest, TestPosition position, string description) { var test = new TestBuilder(_nativeTestFactory.ForTest(_fixtureFactory, position, globalSetupManager)); NameGenator.NameTest(description, parentTest, test); return test; }
public void NameTest(string testShortName, TestBuilder parentTest, TestBuilder test) { test.Shortname = testShortName; test.FullName = parentTest.FullName + ", " + testShortName; test.MultilineName = parentTest.MultilineName + ",\n" + testShortName; IncrementTestNameUntilItsNot(test, name => _globallyAccumulatedTestNames.ContainsKey(name)); _globallyAccumulatedTestNames[test.FullName] = NameIs.Reserved; }
public void NameFork(string testShortName, TestBuilder parentTest, TestBuilder test) { test.Shortname = testShortName; test.FullName = parentTest.FullName + ", " + testShortName; test.MultilineName = parentTest.MultilineName + ",\n" + testShortName; IncrementTestNameUntilItsNot(test, IsReserved); _globallyAccumulatedTestNames[test.FullName] = NameIs.Available; }
private void IncrementTestNameUntilItsNot(TestBuilder test, Func<string, bool> condition) { var name = test.FullName; if (condition(name)) { var nextIndex = 1; string suffix; string nextName; do { suffix = "`" + ++nextIndex; nextName = name + suffix; } while (condition(nextName)); test.Shortname = test.Shortname + suffix; test.FullName = test.FullName + suffix; test.MultilineName = test.MultilineName + suffix; } }
private ITestResult CheckResult(string methodName, ResultState expectedResultState, params string[] assertionMessageRegex) { ITestResult result = TestBuilder.RunTestCase(typeof(AssertMultipleFixture), methodName); Assert.That(result.ResultState, Is.EqualTo(expectedResultState), "ResultState"); Assert.That(result.AssertionResults.Count, Is.EqualTo(assertionMessageRegex.Length), "Number of AssertionResults"); Assert.That(result.StackTrace, Is.Not.Null.And.Contains(methodName), "StackTrace"); if (result.AssertionResults.Count > 0) { int numFailures = result.AssertionResults.Count; if (expectedResultState == ResultState.Error) { --numFailures; } if (numFailures > 1) { Assert.That(result.Message, Contains.Substring("Multiple failures or warnings in test:")); } int i = 0; foreach (var assertion in result.AssertionResults) { // Since the order of argument evaluation is not guaranteed, we don't // want 'i' to appear more than once in the Assert statement. string errmsg = string.Format("AssertionResult {0}", i + 1); Assert.That(assertion.Message, Does.Match(assertionMessageRegex[i++]), errmsg); Assert.That(result.Message, Contains.Substring(assertion.Message), errmsg); // NOTE: This test expects the stack trace to contain the name of the method // that actually caused the failure. To ensure it is not optimized away, we // compile the testdata assembly with optimizations disabled. Assert.That(assertion.StackTrace, Is.Not.Null.And.Contains(methodName), errmsg); } } return(result); }
private async void ShouldNotReturnTokenWhenErrorResponse(HttpStatusCode statusCode) { var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); const string centralRegistryRootUrl = "http://someUrl"; var expectedUri = new Uri($"{centralRegistryRootUrl}/{PATH_SESSIONS}"); var configuration = new GatewayConfiguration { Url = centralRegistryRootUrl, ClientId = TestBuilder.RandomString(), ClientSecret = TestBuilder.RandomString() }; var response = JsonConvert.SerializeObject(new { error = "some failure happened" }); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(response, Encoding.UTF8, MediaTypeNames.Application.Json) }) .Verifiable(); var client = new GatewayClient(httpClient, configuration); var result = await client.Authenticate(); result.HasValue.Should().BeFalse(); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post && message.RequestUri == expectedUri), ItExpr.IsAny <CancellationToken>()); }
public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown() { IgnoredFixture fixture = new IgnoredFixture(); TestSuite suite = new TestSuite("IgnoredFixtureSuite"); TestSuite fixtureSuite = TestBuilder.MakeFixture(fixture.GetType()); suite.Fixture = fixture; NUnit.Core.TestCase testCase = (NUnit.Core.TestCase)fixtureSuite.Tests[0]; suite.Add(fixtureSuite); fixtureSuite.Run(NullListener.NULL); Assert.IsFalse(fixture.setupCalled, "TestFixtureSetUp called running fixture"); Assert.IsFalse(fixture.teardownCalled, "TestFixtureTearDown called running fixture"); suite.Run(NullListener.NULL); Assert.IsFalse(fixture.setupCalled, "TestFixtureSetUp called running enclosing suite"); Assert.IsFalse(fixture.teardownCalled, "TestFixtureTearDown called running enclosing suite"); testCase.Run(NullListener.NULL); Assert.IsFalse(fixture.setupCalled, "TestFixtureSetUp called running a test case"); Assert.IsFalse(fixture.teardownCalled, "TestFixtureTearDown called running a test case"); }
public void MatchFromTopLevelTypeRelationshipUsingBaseTypeFromPolymorphicListTest() { var people = Enumerable.Range(1, 10).Select(z => new Order1 { OrderId = z, OrderDate = DateTime.Today.AddDays(z) }).ToList(); var links = Enumerable.Range(1, 10).Select(z => new LinkedClass1 { OrderId = z, Id = z * 2 }).ToList(); var pool = new TestBuilder().CreateEntityPool(); pool.AddEntities(people.OfType <Order>()); pool.AddEntities(links); Assert.IsTrue(people.All(x => x.ProductLines.All(c => c.OrderId == x.OrderId))); Assert.IsTrue(people.All(c => c.Link1.OrderId == c.OrderId)); }
public async Task SubmitFlightPlanAsync_ReturnsFlightPlan() { var flightPlan = new FlightPlan() { Id = "1a2b", ShipId = "3c4e", Departure = "AB", Destination = "CD" }; var builder = new TestBuilder() .WithMethod(Method.POST) .WithResource($"users/username/flight-plans") .WithPayload("flightplan", flightPlan) .WithParameter("shipId", flightPlan.ShipId) .WithParameter("destination", flightPlan.Destination); var client = builder.Build(); var result = await client.SubmitFightPlanAsync(flightPlan.ShipId, flightPlan.Destination); builder.MockRestClient.Verify(); Assert.IsNotNull(result); }
public void Builders_DatBuilder_setFamilyFromParent_ExBrokenFamily() { builder.KeyColumnName = "DOCID"; builder.RepresentativeBuilders = null; builder.PathPrefix = ""; builder.SetHeader(records[0]); Document parent = builder.BuildDocument(records[2]); Document doc = builder.BuildDocument(records[3]); Dictionary <string, Document> docs = new Dictionary <string, Document>(); Dictionary <string, Document> paternity = new Dictionary <string, Document>(); string childColName = "ATTCHIDS"; docs.Add(parent.Key, parent); paternity.Add(doc.Key, parent); parent.Metadata[childColName] = String.Empty; TestBuilder testBuilder = new TestBuilder(); testBuilder.ParentColumnName = "BEGATT"; testBuilder.ChildColumnName = childColName; testBuilder.ChildSeparator = ";"; testBuilder.setFamilyFromParent(doc, docs, paternity); }
public void HandleExceptionInFixtureConstructor() { TestSuite suite = TestBuilder.MakeFixture(typeof(ExceptionInConstructor)); TestResult result = suite.Run(NullListener.NULL, TestFilter.Empty); // should have one suite and one fixture ResultSummarizer summ = new ResultSummarizer(result); Assert.AreEqual(1, summ.TestsRun); Assert.AreEqual(0, summ.TestsNotRun); Assert.AreEqual(ResultState.Error, result.ResultState); Assert.AreEqual("System.Exception : This was thrown in constructor", result.Message, "TestSuite Message"); Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null"); TestResult testResult = ((TestResult)result.Results[0]); Assert.IsTrue(testResult.Executed, "Testcase should have executed"); Assert.AreEqual("TestFixtureSetUp failed in ExceptionInConstructor", testResult.Message, "TestSuite Message"); Assert.AreEqual(FailureSite.Parent, testResult.FailureSite); Assert.AreEqual(testResult.StackTrace, testResult.StackTrace, "Test stackTrace should match TestSuite stackTrace"); }
public async Task ReturnOtpValidResponse() { var sessionId = TestBuilder.Faker().Random.Hash(); var otpToken = TestBuilder.Faker().Random.String(); var otpRequest = new OtpVerificationRequest(otpToken); otpRepository .Setup(e => e.GetWith(sessionId)) .ReturnsAsync(Option.Some(new OtpRequest { SessionId = sessionId, RequestedAt = DateTime.Now.ToUniversalTime(), OtpToken = otpToken })); var response = await otpController.VerifyOtp(sessionId, otpRequest); otpRepository.Verify(); response.Should().NotBeNull() .And.Subject.As <OkObjectResult>() .Value.Should().BeEquivalentTo(new Response(ResponseType.OtpValid, "Valid OTP")); }
public void CanExcludeRuntime() { bool isNetCore; Type monoRuntimeType = Type.GetType("Mono.Runtime", false); bool isMono = monoRuntimeType != null; #if NETCOREAPP2_0 isNetCore = true; #else isNetCore = false; #endif const string methodName = nameof(TestCaseAttributeFixture.MethodWithExcludeRuntime); TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), methodName); Test testCase1 = TestFinder.Find($"{methodName}(1)", suite, false); Test testCase2 = TestFinder.Find($"{methodName}(2)", suite, false); Test testCase3 = TestFinder.Find($"{methodName}(3)", suite, false); if (isNetCore) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); } else if (isMono) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); } }
protected IBuilder Activate(BusConfiguration busConfiguration, ConfigBase featureConfig, string connectionString = "") { var builder = new TestBuilder(); busConfiguration.UseContainer(builder); var configure = (Configure)typeof(BusConfiguration).GetMethod("BuildConfiguration", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(busConfiguration, new object[0]); var featureContext = (FeatureConfigurationContext)typeof(FeatureConfigurationContext).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(Configure) }, new ParameterModifier[0]).Invoke(new object[] { configure }); var settings = busConfiguration.GetSettings(); featureConfig.SetUpDefaults(settings); featureConfig.Configure(featureContext, connectionString); builder.CallAllFactories(); Builder = configure.Builder; PipelineExecutor = new PipelineExecutor(settings, configure.Builder); return(configure.Builder); }
public static void When_NewAwayGoal_ReturnsAwayTeamGoalEvent() { var current = new List <Fixture> { TestBuilder.NoGoals(fixtureCode: 1) }; var latest = new List <Fixture> { TestBuilder.AwayTeamGoal(fixtureCode: 1, goals: 1, minutes: 72) }; var events = LiveEventsExtractor.GetUpdatedFixtureEvents(latest, current, new List <Player> { TestBuilder.Player() }, new List <Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam() }); var awayGoalEvent = events.First(); Assert.Equal(123, awayGoalEvent.StatMap[StatType.GoalsScored].First().Player.Id); Assert.Equal(TeamType.Away, awayGoalEvent.StatMap[StatType.GoalsScored].First().Team); Assert.Equal(72, awayGoalEvent.FixtureScore.Minutes); }
public static void TestResultSchemaMatches() { Assert.Multiple(() => { var result = TestBuilder.RunTestFixture(typeof(MockTestFixture)); var xml = new StringWriter(); new NUnit3XmlOutputWriter().WriteResultFile( result, xml, runSettings: new Dictionary <string, object> { ["TestDictionary"] = new Dictionary <string, string> { ["TestKey"] = "TestValue", ["ValuelessKey"] = null } }, filter: TestFilter.FromXml("<filter><id>x</id><or><not><cat re='1'>c</cat></not><and><prop name='x'>v</prop></and></or></filter>")); SchemaTestUtils.AssertValidXml(xml.ToString(), "TestResult.xsd"); }); }
private async void ReturnTransactionId() { var consentMangerId = TestBuilder.Faker().Random.String(); var transactionId = TestBuilder.Faker().Random.Hash(); var request = TestBuilder.HealthInformationRequest(transactionId); var expectedResponse = new HealthInformationTransactionResponse(transactionId); var correlationId = Uuid.Generate().ToString(); dataFlow.Setup(d => d.HealthInformationRequestFor(request, consentMangerId, correlationId)) .ReturnsAsync( new Tuple <HealthInformationTransactionResponse, ErrorRepresentation>(expectedResponse, null)); var response = await dataFlowController.HealthInformationRequestFor(request, correlationId, consentMangerId); dataFlow.Verify(); response.Should() .NotBeNull() .And .Subject.As <OkObjectResult>() .Value .Should() .BeEquivalentTo(expectedResponse); }
public void CheckRandomResult(string methodName) { var result = TestBuilder.RunParameterizedMethodSuite(typeof(RandomAttributeFixture), methodName); Assert.That(result.Children.Count(), Is.EqualTo(RandomAttributeFixture.COUNT)); if (result.ResultState != ResultState.Success) { var msg = new StringBuilder(); msg.AppendFormat("Unexpected Result: {0}\n", result.ResultState); if (result.ResultState.Site == FailureSite.Child) { foreach (var child in result.Children) { msg.AppendFormat(" {0}: {1}\n", child.Name, child.ResultState); msg.AppendFormat("{0}\n", child.Message); } } Assert.Fail(msg.ToString()); } }
async void ShouldUpdateConsentArtefactAsExpired() { var consentController = new ConsentController(consentRepository.Object); const string consentMangerId = "consentMangerId"; var consentArtefactRequest = TestBuilder.ConsentArtefactRequest(); consentRepository.Setup(x => x.AddAsync( new Consent(consentArtefactRequest.ConsentDetail.ConsentId, consentArtefactRequest.ConsentDetail, consentArtefactRequest.Signature, ConsentStatus.GRANTED, consentMangerId) )); consentRepository.Setup(x => x.UpdateAsync( consentArtefactRequest.ConsentId, ConsentStatus.EXPIRED) ); var okObjectResult = await consentController.StoreConsent(consentMangerId, consentArtefactRequest) as NoContentResult; consentRepository.Verify(); okObjectResult.StatusCode.Equals(StatusCodes.Status204NoContent); }
private void CreatetSQLtTest(object sender, EventArgs e) { try { CallWrapper(); var dte = (DTE)GetService(typeof(DTE)); if (dte.ActiveDocument == null) { return; } var doc = dte.ActiveDocument.Object("TextDocument") as TextDocument; if (null == doc) { return; } var ep = doc.StartPoint.CreateEditPoint(); ep.EndOfDocument(); var length = ep.AbsoluteCharOffset; ep.StartOfDocument(); var originalText = ep.GetText(length); var builder = new TestBuilder(originalText, dte.ActiveDocument.ProjectItem.ContainingProject); builder.Go(); // builder.CreateTests(); } catch (Exception ex) { OutputPane.WriteMessage("Exception creating tSQLt tests, error: {0}", ex.Message); } }
private static State CreateSingleFinishedFixturesScenario() { var playerClient = A.Fake <IGlobalSettingsClient>(); A.CallTo(() => playerClient.GetGlobalSettings()).Returns( new GlobalSettings { Teams = new List <Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam() }, Players = new List <Player> { TestBuilder.Player(), TestBuilder.OtherPlayer() } }); var fixtureClient = A.Fake <IFixtureClient>(); A.CallTo(() => fixtureClient.GetFixturesByGameweek(1)).Returns(new List <Fixture> { TestBuilder.AwayTeamGoal(888, 1), TestBuilder.AwayTeamGoal(999, 1) }).Once() .Then.Returns( new List <Fixture> { TestBuilder.AwayTeamGoal(888, 1), TestBuilder.AwayTeamGoal(999, 1).FinishedProvisional() .WithProvisionalBonus(TestBuilder.Player().Id, 10) .WithProvisionalBonus(TestBuilder.OtherPlayer().Id, 20) }); return(CreateBaseScenario(fixtureClient, playerClient)); }
private void ShouldProcessMessage() { var collect = new Mock <ICollect>(); var dataFlowClient = new Mock <DataFlowClient>(MockBehavior.Strict, null, null, null); var dataEntryFactory = new Mock <DataEntryFactory>(); var dataFlowMessageHandler = new DataFlowMessageHandler(collect.Object, dataFlowClient.Object, dataEntryFactory.Object); var transactionId = TestBuilder.Faker().Random.Uuid().ToString(); var dataRequest = TestBuilder.DataRequest(transactionId); var careBundles = new List <CareBundle> { new CareBundle("careContextReference", new Bundle()) }; var entries = new Entries(careBundles); var data = Option.Some(entries); var content = TestBuilder.Faker().Random.String(); var checksum = TestBuilder.Faker().Random.Hash(); var entriesList = new List <Entry> { new Entry(content, MediaTypeNames.Application.Json, checksum, null, "careContextReference") }; var requestKeyMaterial = TestBuilder.KeyMaterialLib(); collect.Setup(c => c.CollectData(dataRequest)).ReturnsAsync(data); var keyMaterial = TestBuilder.KeyMaterial(); var encryptedEntriesValue = new EncryptedEntries(entriesList.AsEnumerable(), keyMaterial); var encryptedEntries = Option.Some(encryptedEntriesValue); dataEntryFactory.Setup(e => e.Process(entries, requestKeyMaterial, transactionId)) .Returns(encryptedEntries); dataFlowClient.Setup(c => c.SendDataToHiu(dataRequest, encryptedEntriesValue.Entries, encryptedEntriesValue.KeyMaterial)).Verifiable(); dataFlowMessageHandler.HandleDataFlowMessage(dataRequest); collect.VerifyAll(); dataEntryFactory.Verify(); }
/// <summary> /// Creates the <see cref="Expression"/> representing the binding restrictions. /// </summary> /// <returns>The expression tree representing the restrictions.</returns> public Expression ToExpression() { // We could optimize this better, e.g. common subexpression elimination // But for now, it's good enough. if (this == Empty) { return(Expression.Constant(true)); } var testBuilder = new TestBuilder(); // Visit the tree, left to right. // Use an explicit stack so we don't stack overflow. // // Left-most node is on top of the stack, so we always expand the // left most node each iteration. var stack = new Stack <BindingRestrictions>(); stack.Push(this); do { var top = stack.Pop(); var m = top as MergedRestriction; if (m != null) { stack.Push(m.Right); stack.Push(m.Left); } else { testBuilder.Append(top); } } while (stack.Count > 0); return(testBuilder.ToExpression()); }
public void CanExcludePlatform() { bool isLinux = OSPlatform.CurrentPlatform.IsUnix; bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX; const string methodName = nameof(TestCaseAttributeFixture.MethodWithExcludePlatform); TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), methodName); Test testCase1 = TestFinder.Find($"{methodName}(1)", suite, false); Test testCase2 = TestFinder.Find($"{methodName}(2)", suite, false); Test testCase3 = TestFinder.Find($"{methodName}(3)", suite, false); Test testCase4 = TestFinder.Find($"{methodName}(4)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else if (isMacOSX) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable)); } }
public void ShouldListAccounts() { var builder = TestBuilder.Begin() .AsUser(); var accountModels = new List <AccountModel> { new AccountModel { Name = "assets:checking:boa" }, new AccountModel { Name = "expenses:food" }, }; foreach (var account in accountModels) { builder.UpsertAccount(account); } var response = builder.ExecuteRequest(new ListAccountsRequest()).Result; accountModels.AssertEquals(response.Items); }
public void AssertMultipleFails(string methodName, int asserts, params string[] failureMessageRegex) { var result = TestBuilder.RunTestCase(typeof(AssertMultipleFailureFixture), methodName); Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); Assert.That(result.AssertCount, Is.EqualTo(asserts), "AssertCount"); int expectedFailures = failureMessageRegex.Length; int actualFailures = result.AssertionResults.Count; Assert.That(actualFailures, Is.EqualTo(expectedFailures), "FailureCount"); if (actualFailures > 0) { Assert.That(result.Message, Contains.Substring( string.Format("Multiple Assert block had {0} failure(s)", actualFailures))); int i = 0; foreach (var failure in result.AssertionResults) { // Since the order of argument evaluation is not guaranteed, we don't // want 'i' to appear more than once in the Assert statement. string errmsg = string.Format("AssertionResult {0}", i + 1); Assert.That(failure.Message, Does.Match(failureMessageRegex[i++]), errmsg); Assert.That(result.Message, Contains.Substring(failure.Message), "Failure message should contain AssertionResult message"); // NOTE: This test expects the stack trace to contain the name of the method // that actually caused the failure. To ensure it is not optimized away, we // compile the testdata assembly with optimizations disabled. Assert.That(failure.StackTrace, Is.Not.Null.And.Contains(methodName)); } Assert.That(result.StackTrace, Is.Not.Null.And.Contains(methodName)); } }
public void RunningTestsThroughFixtureGivesCorrectResults() { ITestResult result = TestBuilder.RunTestFixture(fixtureType); ResultSummary summary = new ResultSummary(result); Assert.That( summary.ResultCount, Is.EqualTo(TestMethodSignatureFixture.Tests)); Assert.That( summary.TestsRun, Is.EqualTo(TestMethodSignatureFixture.Runnable)); //Assert.That( // summary.NotRunnable, // Is.EqualTo(TestMethodSignatureFixture.NotRunnable)); //Assert.That( // summary.Errors, // Is.EqualTo(TestMethodSignatureFixture.Errors)); Assert.That( summary.Failures, Is.EqualTo(TestMethodSignatureFixture.Failures + TestMethodSignatureFixture.Errors)); Assert.That( summary.TestsNotRun, Is.EqualTo(TestMethodSignatureFixture.NotRunnable)); }
public void Create_ChecksCollectionSizeForComplexClassType() { var builderMock = new Mock <IBuilder>(); builderMock.Setup(b => b.Build(typeof(ComplexClassType))).Returns(new ComplexClassType()); var registry = new TypeRegistry <Range>(); registry.SetForType <ComplexClassType>(new Range(20, 20)); var builder = new TestBuilder { CollectionSizes = registry, DefaultCollectionSize = new Range(10, 10), BuildDepth = 10 }; var session = new BuildSession(builder, null, new Random(10)); var list = CreateAndGenerate <ComplexClassType[]>(builderMock.Object, session); Assert.AreEqual(20, list.Length); foreach (var result in list) { Assert.IsInstanceOf <ComplexClassType>(result); Assert.IsNotNull(result); } }
/// <summary> /// Creates the <see cref="Expression"/> representing the binding restrictions. /// </summary> /// <returns>The expression tree representing the restrictions.</returns> public Expression ToExpression() { // We could optimize this better, e.g. common subexpression elimination // But for now, it's good enough. if (this == Empty) { return Expression.Constant(true); } var testBuilder = new TestBuilder(); // Visit the tree, left to right. // Use an explicit stack so we don't stack overflow. // // Left-most node is on top of the stack, so we always expand the // left most node each iteration. var stack = new Stack<BindingRestrictions>(); stack.Push(this); do { var top = stack.Pop(); var m = top as MergedRestriction; if (m != null) { stack.Push(m.Right); stack.Push(m.Left); } else { testBuilder.Append(top); } } while (stack.Count > 0); return testBuilder.ToExpression(); }
public void CanSpecifyMultipleCategories() { Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithMultipleCategories)); Assert.AreEqual(new string[] { "X", "Y", "Z" }, fixture.Categories); }
public void CanSpecifyCategory() { Test fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.TestFixtureWithSingleCategory)); Assert.AreEqual(new string[] { "XYZ" }, fixture.Categories); }
public void MakeFixture() { fixture = TestBuilder.MakeFixture(typeof(NUnit.TestData.ParameterizedTestFixture)); }
public void BadConstructorRunsWithSetUpError() { var result = TestBuilder.RunTestFixture(typeof(BadCtorFixture)); Assert.That(result.ResultState, Is.EqualTo(ResultState.SetUpError)); }
public void CapturesNoArgumentsForConstructorWithoutArgsSupplied() { var fixture = TestBuilder.MakeFixture(typeof(RegularFixtureWithOneTest)); Assert.That(fixture.Arguments, Is.EqualTo(new object[0])); }
public void CapturesArgumentsForConstructorWithArgsSupplied() { var fixture = TestBuilder.MakeFixture(typeof(FixtureWithArgsSupplied)); Assert.That(fixture.Arguments, Is.EqualTo(new[] { 7, 3 })); }
public void ReserveName(TestBuilder test) { IncrementTestNameUntilItsNot(test, name => _globallyAccumulatedTestNames.ContainsKey(name) && _globallyAccumulatedTestNames[name] == NameIs.Reserved); _globallyAccumulatedTestNames[test.FullName] = NameIs.Reserved; }
public void SetupTest() { _testBuilder = new TestBuilder(GetControlFactory()); }
public Expression ToExpression() { if (this == Empty) { return Expression.Constant(true); } TestBuilder builder = new TestBuilder(); Stack<BindingRestrictions> stack = new Stack<BindingRestrictions>(); stack.Push(this); do { BindingRestrictions restrictions = stack.Pop(); MergedRestriction restriction = restrictions as MergedRestriction; if (restriction != null) { stack.Push(restriction.Right); stack.Push(restriction.Left); } else { builder.Append(restrictions); } } while (stack.Count > 0); return builder.ToExpression(); }
internal override Expression GetExpression() { // We could optimize this better, e.g. common subexpression elimination // But for now, it's good enough. var testBuilder = new TestBuilder(); // Visit the tree, left to right. // Use an explicit stack so we don't stack overflow. // // Left-most node is on top of the stack, so we always expand the // left most node each iteration. var stack = new Stack<BindingRestrictions>(); BindingRestrictions top = this; for (;;) { var m = top as MergedRestriction; if (m != null) { stack.Push(m.Right); top = m.Left; } else { testBuilder.Append(top); if (stack.Count == 0) { return testBuilder.ToExpression(); } top = stack.Pop(); } } }