static void Main(string[] args) { var endOfRec = DateTime.Now.Add(TimeSpan.FromSeconds(30)); using (var writer = new AviWriter("test.avi") { FramesPerSecond = 15, EmitIndex1 = true }) { var stream = writer.AddVideoStream(); stream.Width = Screen.PrimaryScreen.WorkingArea.Width; stream.Height = Screen.PrimaryScreen.WorkingArea.Height; stream.Codec = KnownFourCCs.Codecs.Uncompressed; stream.BitsPerPixel = BitsPerPixel.Bpp32; var googleChrome = new TestCase(); Task.Factory.StartNew(() => { googleChrome.Scenario("http://www.google.com", "что посмотреть сегодня?"); }); var buffer = new byte[Screen.PrimaryScreen.WorkingArea.Width * Screen.PrimaryScreen.WorkingArea.Height * 4]; while (!TestCase.isFinished) { GetScreenshot(buffer); stream.WriteFrame(true, buffer, 0, buffer.Length); } } Console.WriteLine("Execution Done"); }
public IEnumerable<Violation> Apply(TestCase testCase) { var calledAssertingMethods = testCase.GetCalledAssertingMethods(); var tracker = new MethodValueTracker(testCase.TestMethod); // For each asserting method with >= 1 parameters: foreach (var cm in calledAssertingMethods) { var methodRef = cm.MethodReference; var parameterPurposes = testCase.Framework.GetParameterPurposes(methodRef); if (!IsSingleTruthCheckingMethod(methodRef, parameterPurposes)) continue; foreach (var valueGraph in tracker.ValueGraphs) { IList<MethodValueTracker.Value> consumedValues = tracker.GetConsumedValues(valueGraph, cm.Instruction).ToList(); if (consumedValues.Count == 0) continue; // not part of value graph var interestingValue = consumedValues[0]; var producers = UltimateProducers(interestingValue); if (producers.Count > 1) { yield return new Violation(this, testCase, cm.Instruction, string.Format("{0}.{1} performs a boolean test on a composite boolean value", cm.MethodReference.DeclaringType.Name, cm.MethodReference.Name)); } } } }
private ObjectModel.TestResult CreateTest(TestData test, TestStepRun stepRun, TestCase testCase) { ObjectModel.TestResult testResult = new ObjectModel.TestResult(testCase); testResult.DisplayName = test.Name; testResult.ErrorLineNumber = test.CodeLocation.Line; //testResult.ErrorStackTrace testResult.StartTime = stepRun.StartTime; if (stepRun.TestLog.Streams.Count > 0) { testResult.ErrorMessage = stepRun.TestLog.Streams[0].ToString(); } testResult.EndTime = stepRun.EndTime; testResult.Duration = stepRun.Result.Duration; var testStatus = stepRun.Result.Outcome.Status; switch (testStatus) { case TestStatus.Passed: testResult.Outcome = ObjectModel.TestOutcome.Passed; break; case TestStatus.Failed: testResult.Outcome = ObjectModel.TestOutcome.Failed; break; case TestStatus.Skipped: testResult.Outcome = ObjectModel.TestOutcome.Skipped; break; case TestStatus.Inconclusive: testResult.Outcome = ObjectModel.TestOutcome.NotFound; break; } return testResult; }
public TestFailed(Exception ex) { TestCase = new TestCase(); ExceptionType = ex.GetType().FullName; Message = ExceptionUtility.GetMessage(ex); StackTrace = ExceptionUtility.GetStackTrace(ex); }
/// <summary> /// Initializes a new instance of the <see cref="TestCaseFull" /> class. /// </summary> /// <param name="testCase">The test case.</param> /// <param name="testSteps">The test steps.</param> /// <param name="mostRecentResult">The most recent result.</param> /// <param name="executionComment">The execution comment.</param> public TestCaseFull(TestCase testCase, List<TestStep> testSteps, string mostRecentResult, string executionComment) { this.TestCase = testCase; this.TestSteps = testSteps; this.MostRecentResult = mostRecentResult; this.ExecutionComment = executionComment; }
private void DoTest(TestCase test) { var canvas = new Canvas(); canvas.Width = 300; canvas.Height = 700; ICanvasRenderingContext2D ctx = new CanvasRenderingContext2D(canvas, this, true); string url = test(ctx); ctx.commit(); string location = Application.ResourceAssembly.Location; string path = location.Remove(location.LastIndexOf("\\")); var di = new DirectoryInfo(path); url = di.Parent.Parent.Parent.FullName + "\\SharpCanvas.Tests\\" + url; if (File.Exists(url)) { pctOriginal.Source = new BitmapImage(new Uri(url)); pctOriginal.Visibility = Visibility.Visible; } else { pctOriginal.Visibility = Visibility.Hidden; } ctResults.Children.Clear(); ctResults.Children.Add(canvas); }
private void WriteTestCase(string outputDirectory, TestCase currentTestCase) { EnsureDirectoryExists(outputDirectory); File.WriteAllText(Path.Combine(outputDirectory, currentTestCase.Name + ".txt"), currentTestCase.Content); File.WriteAllText(Path.Combine(outputDirectory, currentTestCase.Name + ".json"), currentTestCase.Json); }
static TextWriter tw; //= new StreamReader("A-small-attempt3.in"); #endregion Fields #region Methods static void Main(string[] args) { tr = new StreamReader("C-large-1.in"); int n = Convert.ToInt16(tr.ReadLine()); List<TestCase> testCases = new List<TestCase>(); for (; i < n; i++) { TestCase t = new TestCase(); string[] temp2 = tr.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //string[] temp2 = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); t.lowLimit = Convert.ToInt64(temp2[0]); t.upperLimit = Convert.ToInt64(temp2[1]); testCases.Add(t.processInput()); } tw = new StreamWriter("output.txt"); i = 0; for (; i < testCases.Count-1; i++) { tw.WriteLine("Case #{0}: {1}", (i + 1), testCases[i].output); } tw.Write("Case #{0}: {1}", (i + 1), testCases[i].output); tr.Close(); tw.Close(); //Console.ReadLine(); }
public object PropertyProvider(TestCase testCase, string name) { // Traits filtering if (knownTraits.Contains(name)) { var result = new List<string>(); foreach (var trait in GetTraits(testCase)) if (string.Equals(trait.Key, name, StringComparison.OrdinalIgnoreCase)) result.Add(trait.Value); if (result.Count > 0) return result.ToArray(); } else { // Handle the displayName and fullyQualifierNames independently if (string.Equals(name, FullyQualifiedNameString, StringComparison.OrdinalIgnoreCase)) return testCase.FullyQualifiedName; if (string.Equals(name, DisplayNameString, StringComparison.OrdinalIgnoreCase)) return testCase.DisplayName; } return null; }
private void bAddUnitTest_Click(object sender, RoutedEventArgs e) { TestCase tc = new TestCase(); tc.UT = new UnitTest("?unittest", 0, 0, 0, 0, "a"); // Create blank unit test, and pass it to dialog. tc.ShowDialog(); Singleton.GetSingleton().unitTestSuite.unitTests.Add(tc.UT); // Add test case created in dialog. }
public TestCaseRuleApplication(TestCase testCase, IRule rule, IViolationScorer scorer) { _scorer = scorer; TestCase = testCase; Rule = rule; Apply(); }
private void DoTest(TestCase test) { if (animation.IsStarted) animation.Stop(); Graphics g = ctResults.Panel1.CreateGraphics(); //this.CreateGraphics(); g.Clear(Color.White); var bmp = new Bitmap((int) g.VisibleClipBounds.Width, (int) g.VisibleClipBounds.Height); Graphics tmp = Graphics.FromImage(bmp); var ctx = new CanvasRenderingContext2D(tmp, bmp, new Pen(Color.Black, 1), new Fill(Color.Black), false); string url = test(ctx); g.DrawImage(bmp, 0, 0); var di = new DirectoryInfo(Application.StartupPath); url = di.Parent.Parent.Parent.FullName + "\\SharpCanvas.Tests\\" + url; if (File.Exists(url)) { pctOriginal.Load(url); pctOriginal.Show(); } else { pctOriginal.Hide(); } }
public void DelayTestCaseTest() { DeleteFiles(); int stepDelayDuration = 500; var step = new DelayStep(); step.DelayMilliSeconds = stepDelayDuration; var sw = new Stopwatch(); sw.Start(); step.Execute(new Context()); var actualDuration = sw.ElapsedMilliseconds; Console.WriteLine("Observed delay: {0}", actualDuration); Assert.AreEqual(stepDelayDuration, actualDuration, 20); stepDelayDuration = 5; step.DelayMilliSeconds = stepDelayDuration; var tc = new TestCase(); tc.ExecutionSteps.Add(step); TestCase.SaveToFile(tc, "DelayTestCaseTest.xaml"); var bu = new BizUnit(TestCase.LoadFromFile("DelayTestCaseTest.xaml")); sw = new Stopwatch(); sw.Start(); bu.RunTest(); actualDuration = sw.ElapsedMilliseconds; Console.WriteLine("Observed delay: {0}", actualDuration); Assert.AreEqual(actualDuration, stepDelayDuration, 20); }
// TODO: Write a constructor that takes an out argument of type // TestCase and a second argument of type in that // will have the test case number. This constructor will // determine which test case to encapsulate inside of // the delegate. internal TestCases(out TestCase testCaseDelegate, int testCaseNumber) { _timeToWaitGenerator = new Random(DateTime.Now.Millisecond); switch (testCaseNumber) { case 0: testCaseDelegate = new TestCase(RunAllTestCases); break; case 1: testCaseDelegate = new TestCase(TestCase1); break; case 2: testCaseDelegate = new TestCase(TestCase2); break; case 3: testCaseDelegate = new TestCase(TestCase3); break; default: Console.WriteLine("WARNING: Invalid case number {0} specified. Defaulting to ALL.", testCaseNumber); testCaseDelegate = new TestCase(RunAllTestCases); break; } }
public static IEnumerable<TestCase> GetTests(IEnumerable<string> sourceFiles, ITestCaseDiscoverySink discoverySink) { var tests = new List<TestCase>(); Parallel.ForEach(sourceFiles, s => { var sourceCode = File.ReadAllText(s); var matches = TestFinderRegex.Matches(sourceCode); foreach (Match m in matches) { var methodParts = m.Groups["Method"].Value.Split(new string[] { ".prototype." }, System.StringSplitOptions.None); var testClass = methodParts[0]; var testMethod = methodParts[1]; var testName = m.Groups["Name"].Value; var testDescription = m.Groups["Description"].Value; var testCase = new TestCase(String.Join(".", methodParts), TSTestExecutor.ExecutorUri, s) { CodeFilePath = s, DisplayName = testName, }; if (discoverySink != null) { discoverySink.SendTestCase(testCase); } tests.Add(testCase); } }); return tests; }
internal static IList<TestCase> GetTests(IEnumerable<string> sources, ITestCaseDiscoverySink discoverySink = null, ITestContainer testContainer = null) { IList<TestCase> tests = new List<TestCase>(); foreach (var assemblyFileName in sources) { Assembly assembly = Assembly.LoadFrom(assemblyFileName); var methodsWithMoyaAttributes = assembly.GetTypes() .SelectMany(t => t.GetMethods()) .Where(Reflection.MethodInfoHasMoyaAttribute) .ToArray(); foreach (MethodInfo methodWithMoyaAttributes in methodsWithMoyaAttributes) { var testCase = new TestCase(methodWithMoyaAttributes.Name, Constants.ExecutorUri, assemblyFileName) { Id = Guid.NewGuid() }; tests.Add(testCase); if (discoverySink != null) { discoverySink.SendTestCase(testCase); } if (testContainer != null) { testContainer.AddTestCaseAndMethod(testCase, methodWithMoyaAttributes); } } } return tests; }
public void RunAllTestsInDocument_ShouldExtractAllProjectReferences_And_PassItTo_TestSandbox() { // arrange var project = CreateProject("SampleTestsProject"); string[] allProjectReferences = { "A" }; _solutionExplorerMock.GetAllProjectReferences(project.Name).Returns(allProjectReferences); var testNode = CSharpSyntaxTree.ParseText("[TestFixture]class HelloWorldTests{" + " [Test] public void TestMethod()" + "{}" + "}"); var testClass = testNode.GetRoot().GetClassDeclarationSyntax(); var fixtureDetails = new TestFixtureDetails(); var testCase = new TestCase(fixtureDetails) { SyntaxNode = testClass.GetPublicMethods().Single() }; fixtureDetails.Cases.Add(testCase); _testExtractorMock.GetTestClasses(Arg.Any<CSharpSyntaxNode>()) .Returns(new[] { testClass }); _testExtractorMock.GetTestFixtureDetails(testClass, Arg.Any<ISemanticModel>()).Returns(fixtureDetails); var rewrittenDocument = new RewrittenDocument(testNode, null, false); // act _sut.RunAllTestsInDocument(rewrittenDocument, null, project, new string[0]); // assert _testExecutorEngineMock.Received(1). RunTestFixture(Arg.Is<string[]>(x => x[0] == allProjectReferences[0]), Arg.Any<TestFixtureExecutionScriptParameters>()); }
private void RunTest(ITestExecutionRecorder frameworkHandle, string source, string spec = null) { var results = appDomainRunner.ExecuteSpecifications(source, spec); var query = from result in results from @group in result.Examples from example in @group.Examples select example; foreach (var example in query) { var testCase = new TestCase(example.Reason, ExecutorUri, source) { CodeFilePath = source }; frameworkHandle.RecordStart(testCase); var testResult = new TestResult(testCase) { DisplayName = example.Reason, Duration = new TimeSpan(example.ElapsedTime), }; if (example.Status == ResultStatus.Error) { testResult.Outcome = TestOutcome.Failed; testResult.ErrorMessage = example.Message; testResult.ErrorStackTrace = example.StackTrace; } if (example.Status == ResultStatus.Success) { testResult.Outcome = TestOutcome.Passed; } frameworkHandle.RecordEnd(testCase, testResult.Outcome); frameworkHandle.RecordResult(testResult); } }
public TestCase GetTestCase(TestData testData) { string displayName; var fullName = testData.FullName; var pos = fullName.LastIndexOf('/'); if (pos == -1) { displayName = testData.CodeReference.MemberName; } else { displayName = fullName.Substring(pos + 1); } var testCase = new TestCase(fullName, new Uri(GallioAdapter.ExecutorUri), GetSource(testData)) { CodeFilePath = testData.CodeLocation.Path, LineNumber = testData.CodeLocation.Line, DisplayName = displayName }; testCase.SetPropertyValue(testIdProperty, testData.Id); return testCase; }
public void RunAllTestsInDocument_ShouldExtractAllTestCases() { // arrange var project = CreateProject("SampleTestsProject"); var semanticModel = Substitute.For<ISemanticModel>(); var testNode = CSharpSyntaxTree.ParseText("[TestFixture]class HelloWorldTests{" + " [Test] public void TestMethod()" + "{}" + "}"); var testClass = testNode.GetRoot().GetClassDeclarationSyntax(); var fixtureDetails = new TestFixtureDetails(); var testCase = new TestCase(fixtureDetails) { SyntaxNode = testClass.GetPublicMethods().Single() }; fixtureDetails.Cases.Add(testCase); _testExtractorMock.GetTestClasses(Arg.Any<CSharpSyntaxNode>()) .Returns(new[] { testClass }); _testExtractorMock.GetTestFixtureDetails(Arg.Any<ClassDeclarationSyntax>(), Arg.Any<ISemanticModel>()).Returns(fixtureDetails); var rewrittenDocument = new RewrittenDocument(testNode, null, false); // act _sut.RunAllTestsInDocument(rewrittenDocument, semanticModel, project, new string[0]); // assert _testExtractorMock.Received(1).GetTestFixtureDetails(testClass, semanticModel); }
internal static IEnumerable<TestCase> GetTests(IEnumerable<string> sources, ITestCaseDiscoverySink discoverySink) { //if(!Debugger.IsAttached) // Debugger.Launch(); var tests = new List<TestCase>(); foreach (string source in sources) { var TestNames = GetTestNameFromFile(source); foreach (var testName in TestNames) { var normalizedSource = source.ToLowerInvariant(); var testCase = new TestCase(testName.Key, ProtractorTestExecutor.ExecutorUri, normalizedSource); tests.Add(testCase); testCase.CodeFilePath = source; testCase.LineNumber = testName.Value; if (discoverySink != null) { discoverySink.SendTestCase(testCase); } } } return tests; }
private void btnAdd_Click(object sender, RoutedEventArgs e) { string newTestName; for (int testId = 1; ; ++testId) { newTestName = "case" + testId; if (!TestCases.Any(t => StringComparer.CurrentCultureIgnoreCase.Equals(newTestName, t.Name))) { break; } } var newTestCase = new TestCase { Name = newTestName, Input = "", Output = "", IsSkipped = false, OutputIsKnown = true, }; TestCases.Add(newTestCase); lstTestCases.Items.Add(newTestCase); lstTestCases.SelectedItem = newTestCase; }
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { var validSources = from source in sources where source.EndsWith(StringHelper.GetSearchExpression(), StringComparison.CurrentCultureIgnoreCase) select source; foreach (var source in validSources) { var results = appDomainRunner.ExecuteSpecifications(source); var query = from result in results from @group in result.Examples from example in @group.Examples select example; foreach (var example in query) { var testCase = new TestCase(example.Reason, DefaultTestExecutor.ExecutorUri, source) { CodeFilePath = example.FileName, LineNumber = example.LineNumber }; discoverySink.SendTestCase(testCase); } } }
public void WhenRunningTestsProvidingAssemblySources_ShouldDiscoverAndRunTestsInAssembly() { TestGeneratorAdapter adapter = CreateTestGeneratorAdapter(); TestCase testCase1 = new TestCase("#1", TestGeneratorAdapter.ExecutorUri, "Source1") { LocalExtensionData = new TestContext(testGenerator, new Test("#1")) }; TestCase testCase2 = new TestCase("#1", TestGeneratorAdapter.ExecutorUri, "Source1") { LocalExtensionData = new TestContext(testGenerator, new Test("#1")) }; TestCase testCase3 = new TestCase("#1", TestGeneratorAdapter.ExecutorUri, "Source1") { LocalExtensionData = new TestContext(testGenerator, new Test("#1")) }; testGeneratorDiscoverer.Discover(Arg.Any<IEnumerable<string>>(), Arg.Any<IMessageLogger>()) .Returns(new TestCase[] { testCase1, testCase2, testCase3 }); adapter.RunTests(new string[] { "Some Source" }, runContext, frameworkHandle); frameworkHandle.Received(3).RecordResult(Arg.Is<TestResult>(result => result.TestCase.DisplayName == "#1")); }
public bool IsEnabled (TestCase test) { var attr = test.Attribute as HttpClientTestAttribute; if (attr == null) return false; return (attr.Target & HttpClientTestTarget.Default) != 0; }
public override void AddAll(TestCase test) { // Do like super's base.AddAll(test); // If test invalid if (null == test) { // Error throw new Exception("Invalid test case encountered."); } // For each method in the test case Type type = test.GetType(); foreach (MethodInfo method in type.GetMethods()) { // For each unit test attribute foreach (System.Object obj in method.GetCustomAttributes(typeof(CoroutineUnitTest), false)) { // If attribute is valid Attribute testAtt = obj as Attribute; if (null != testAtt) { // If type has constructors ConstructorInfo[] ci = type.GetConstructors(); if (0 < ci.Length) { // Add the test TestCase tmp = ci[0].Invoke(null) as TestCase; tmp.SetTestMethod(method.Name); coroutineTests.Add(tmp); } } } } }
public void AddChildToTestCase() { TestSuite master = new TestSuite("master", null); TestCase test = new TestCase("test", master); test.AddChild(new TestCase()); }
public override TestResult Run(TestCase testCase) { DateTime start = DateTime.Now; FileLoader.Load(testCase.Instance, this._data); TimeSpan elapsed = DateTime.Now - start; return new TestResult(elapsed, testCase.Instance.Triples.Count, "Triples/Second"); }
private static NaplTestCase SerializeTestCase(TestCase testCase) { var res = new NaplTestCase(); res.arguments.AddRange(testCase.Arguments.Select(SerializeTestValue)); res.expected_result = SerializeTestValue(testCase.ExpectedResult); res.description = testCase.Description; return res; }
public void ConvertToTestCommandWithNullMethodThrows() { Action<TimeZone> dummyAction = _ => { }; var sut = new TestCase<TimeZone>(dummyAction); Assert.Throws<ArgumentNullException>( () => sut.ConvertToTestCommand(null)); }
public async Task IntT_InMem_AccessToken_Get_Expired() { await TestCase.AccessToken_Get_Expired().ConfigureAwait(false); }
public static IEnumerable <string> GetCategories(this TestCase testCase) { var categories = testCase.GetPropertyValue(CategoryList.NUnitTestCategoryProperty) as string[]; return(categories); }
public async Task IntT_InMem_AccessToken_GetOrAdd_WithUser() { await TestCase.AccessToken_GetOrAdd_WithUser().ConfigureAwait(false); }
public void BTA226_CDIS_GetMemberPromotion_Positive() { testCase = new TestCase(TestContext.TestName); listOfTestSteps = new List <TestStep>(); testStep = new TestStep(); String stepName = ""; int index = 0; try { Logger.Info("Test Method Started"); Common common = new Common(this.DriverContext); CDIS_Service_Methods cdis_Service_Method = new CDIS_Service_Methods(common); testStep = TestStepHelper.StartTestStep(testStep); stepName = "Adding member with CDIS service"; Member output = cdis_Service_Method.GetCDISMemberGeneral(); testStep.SetOutput("IpCode: " + output.IpCode + ", Name: " + output.FirstName); Logger.Info("IpCode:" + output.IpCode + ",Name:" + output.FirstName); testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, true, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); IList <VirtualCard> vc = output.GetLoyaltyCards(); testStep = TestStepHelper.StartTestStep(testStep); stepName = "Getting Promotion Definitions from Service"; if (cdis_Service_Method.GetActivePromotionsDefinitionsCount() < 15) { index = 0; } else { index = cdis_Service_Method.GetActivePromotionsDefinitionsCount() - 10; } PromotionDefinitionStruct[] def = cdis_Service_Method.GetPromotionDefinitionsRecent(index); PromotionDefinitionStruct promot = new PromotionDefinitionStruct(); foreach (PromotionDefinitionStruct pd in def) { if (pd.Targeted) { promot = pd; break; } } Logger.Info("Promotion to be added " + promot.Name); testStep.SetOutput("The Targerted Promotion: " + promot.Name + " will be added to the member; Name: " + output.FirstName); testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, true, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); testStep = TestStepHelper.StartTestStep(testStep); stepName = "Adding Promotion to a member from Service"; MemberPromotionStruct promotionCode = cdis_Service_Method.AddMemberPromotion(vc[0].LoyaltyIdNumber, promot.Code); testStep.SetOutput("The Targerted Promotion: " + promot.Name + " with Promotion ID : " + promotionCode.Id + " has been added to member: " + output.FirstName); Logger.Info("MemberPromotion Code : " + promotionCode.Id); testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, true, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); testStep = TestStepHelper.StartTestStep(testStep); stepName = "Verify newly added Promotion from GetMemberpromotions"; GetMemberPromotionsOut memberPromotions = cdis_Service_Method.GetMemberPromotions(vc[0].LoyaltyIdNumber); testStep.SetOutput("Expected value (promotion code from response) is: " + memberPromotions.MemberPromotion[0].Id + " and the actual value (promotion which was added through AddMemberPromotion) is" + promotionCode.Id); Assert.AreEqual(promotionCode.Id, memberPromotions.MemberPromotion[0].Id, "Expected value (promotion code from response) is" + memberPromotions.MemberPromotion[0].Id + "Actual value (promotion which was added through AddMemberPromotion) is" + promotionCode.Id); Logger.Info("MemberPromotion Code : " + memberPromotions.MemberPromotion[0].Id); testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, true, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); testStep = TestStepHelper.StartTestStep(testStep); stepName = "Validating the response from database"; String dbresponse = DatabaseUtility.GetMemberPromotionsCodeUsingIdFromDBSOAP(output.IpCode + ""); testStep.SetOutput("Member Promotion Code from database:" + dbresponse); Assert.AreEqual(memberPromotions.MemberPromotion[0].Id + "", dbresponse, "Expected value is" + memberPromotions.MemberPromotion[0].Id + "Actual value is" + dbresponse); testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, true, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); testCase.SetStatus(true); } catch (Exception e) { testStep = TestStepHelper.EndTestStep(testCase, testStep, stepName, false, DriverContext.SendScreenshotImageContent("API")); listOfTestSteps.Add(testStep); testCase.SetStatus(false); testCase.SetErrorMessage(e.Message); Assert.Fail(e.Message); } finally { testCase.SetTestCaseSteps(listOfTestSteps); testCase.SetEndTime(new StringHelper().GetFormattedDateTimeNow()); listOfTestCases.Add(testCase); } }
public static void AddTrait(this TestCase testCase, string name, string value) { testCase?.Traits.Add(new Trait(name, value)); }
public async Task IntT_InMem_AccessToken_Delete_ByUser_And_Feature() { await TestCase.AccessToken_Delete_ByUser_And_Feature().ConfigureAwait(false); }
public TestCaseSandbox(TestCase testCase) : this(testCase, NPath.SystemTemp) { }
public void RecordStart(TestCase testCase) { }
// NOTE: These constructors are protected internal to allow 3rd parties to // do unit testing of their data collectors. // // We do not want to make the constructors of this class public as it // would lead to a great deal of user error when they start creating // their own data collection context instances to log errors/warnings // or send files with. The potential for this type of error still // exists by having the protected constructor, but it is less likely // and we have added safeguards in our DataCollectinLogger and // DataCollectionDataSink to safeguard against derived types being // passed to us. // // In order to create mock instances of the DataCollectionContext for // unit testing purposes, 3rd parties can derive from this class and // have public constructors. This will allow them to instantiate their // class and pass to us for creating data collection events. /// <summary> /// Constructs DataCollection Context for in process data collectors /// </summary> /// <param name="testCase">test case to identify the context</param> public DataCollectionContext(TestCase testCase) { this.TestCase = testCase; }
private static void TestCase_OnExecutionBegin(TestCase testCase, TestCaseBeginExecutionArgs args) { LogEvent.Info(message: $"Beginning test case execution \"{testCase.Title}\""); }
public void RecordEnd(TestCase testCase, TestOutcome outcome) { }
public void SendTestCase(TestCase discoveredTest) { Tests.Add(discoveredTest); }
public async Task IntT_InMem_AccessToken_AssertExists_Missing() { await TestCase.AccessToken_AssertExists_Missing().ConfigureAwait(false); }
public void Test( [ValueSource(nameof(TestCases))] TestCase testCase, [ValueSource(nameof(BufferSizes))] BufferSize bufferSize) { var configMock = new Mock <IConfig>(); int usingBufferSize = LargeBufferSize; if (bufferSize < BufferSize.Large) { usingBufferSize = sizeof(ulong); if (bufferSize != BufferSize.Min) { ++usingBufferSize; } } configMock .SetupGet(o => o.UsingBufferLength) .Returns(usingBufferSize); var physicalBufferLength = usingBufferSize + Consts.BufferReadingEnsurance; configMock .SetupGet(o => o.PhysicalBufferLength) .Returns(physicalBufferLength); ISortingSegmentsSupplier sortingSegmentsSupplier = new SortingSegmentsSupplier( configMock.Object); var lineIndexesExtractorMock = new Mock <ILinesIndexesExtractor>(); IGroupSorter groupSorter = new GroupSorter( sortingSegmentsSupplier, lineIndexesExtractorMock.Object); var groupBytesCount = testCase.GroupBytes.Length; var groupBuffersCount = (int)Math.Ceiling((double) groupBytesCount / usingBufferSize); var buffersCount = BuffersOffset + groupBuffersCount + OverBuffersCount; byte[][] buffers = Enumerable .Range(0, buffersCount) .Select(_ => new byte[physicalBufferLength]) .ToArray(); for (int i = 0; i < groupBuffersCount - 1; i++) { Array.Copy(testCase.GroupBytes, i * usingBufferSize, buffers[BuffersOffset + i], 0, usingBufferSize); } Array.Copy(testCase.GroupBytes, (groupBuffersCount - 1) * usingBufferSize, buffers[BuffersOffset + groupBuffersCount - 1], 0, groupBytesCount % usingBufferSize); var lines = new LineIndexes[LinesStorageLength]; var segments = new ulong[LinesStorageLength]; var groupMock = new Mock <IGroup>(); groupMock .SetupGet(o => o.BytesCount) .Returns(groupBytesCount); groupMock .SetupGet(o => o.Buffers) .Returns(new ArraySegment <byte[]>( buffers, BuffersOffset, groupBuffersCount)); groupMock .SetupGet(o => o.Lines) .Returns(new ArraySegment <LineIndexes>( lines, LinesRangeOffset, testCase.InputLines.Length)); groupMock .SetupGet(o => o.SortingSegments) .Returns(new ArraySegment <ulong>( segments, LinesRangeOffset, testCase.InputLines.Length)); lineIndexesExtractorMock .Setup(o => o.ExtractIndexes(groupMock.Object)) .Callback(() => Array.Copy(testCase.InputLines, 0, lines, LinesRangeOffset, testCase.InputLines.Length)); groupSorter.Sort(groupMock.Object); var resultLines = lines .Skip(LinesRangeOffset) .Take(testCase.InputLines.Length) .Select(o => o.Start) .ToArray(); // Console.WriteLine(string.Join(" ", testCase.ExpectedSortedLines)); // Console.WriteLine(string.Join(" ", resultLines)); CollectionAssert.AreEqual( testCase.ExpectedSortedLines, resultLines); }
public async Task IntT_InMem_AccessToken_Get_ForUserContentAndFeature() { await TestCase.AccessToken_Get_ForUserContentAndFeature().ConfigureAwait(false); }
public async Task IntT_InMem_AccessToken_Create_ForUser_ValueLength() { await TestCase.AccessToken_Create_ForUser_ValueLength().ConfigureAwait(false); }
public async Task IntT_InMem_AccessToken_Create_ForUserAndContent() { await TestCase.AccessToken_Create_ForUserAndContent().ConfigureAwait(false); }
public async Task IntT_InMem_AccessToken_UpdateMissing() { await TestCase.AccessToken_UpdateMissing().ConfigureAwait(false); }
public TestCaseCompilationMetadataProvider(TestCase testCase, AssemblyDefinition fullTestCaseAssemblyDefinition) : base(testCase, fullTestCaseAssemblyDefinition) { }
public void DesignModeClientWithRunSelectedTestCasesShouldDeserializeTestsWithTraitsCorrectly() { // Arrange. var testCase = new TestCase("A.C.M", new Uri("d:\\executor"), "A.dll"); testCase.Traits.Add(new Trait("foo", "bar")); var testList = new System.Collections.Generic.List <TestCase> { testCase }; var testRunPayload = new TestRunRequestPayload { RunSettings = null, TestCases = testList }; var getProcessStartInfoMessage = new Message { MessageType = MessageType.TestRunSelectedTestCasesDefaultHost, Payload = JToken.FromObject("random") }; var sessionEnd = new Message { MessageType = MessageType.SessionEnd }; TestRunRequestPayload receivedTestRunPayload = null; var allTasksComplete = new ManualResetEvent(false); // Setup mocks. this.mockCommunicationManager.Setup(cm => cm.WaitForServerConnection(It.IsAny <int>())).Returns(true); this.mockCommunicationManager.Setup(cm => cm.DeserializePayload <TestRunRequestPayload>(getProcessStartInfoMessage)) .Returns(testRunPayload); this.mockTestRequestManager.Setup( trm => trm.RunTests( It.IsAny <TestRunRequestPayload>(), It.IsAny <ITestHostLauncher>(), It.IsAny <ITestRunEventsRegistrar>(), It.IsAny <ProtocolConfig>())) .Callback( (TestRunRequestPayload trp, ITestHostLauncher testHostManager, ITestRunEventsRegistrar testRunEventsRegistrar, ProtocolConfig config) => { receivedTestRunPayload = trp; allTasksComplete.Set(); }); this.mockCommunicationManager.SetupSequence(cm => cm.ReceiveMessage()) .Returns(getProcessStartInfoMessage) .Returns(sessionEnd); // Act. this.designModeClient.ConnectToClientAndProcessRequests(0, this.mockTestRequestManager.Object); // wait for the internal spawned of tasks to complete. allTasksComplete.WaitOne(1000); // Assert. Assert.IsNotNull(receivedTestRunPayload); Assert.IsNotNull(receivedTestRunPayload.TestCases); Assert.AreEqual(1, receivedTestRunPayload.TestCases.Count); // Validate traits var traits = receivedTestRunPayload.TestCases.ToArray()[0].Traits; Assert.AreEqual("foo", traits.ToArray()[0].Name); Assert.AreEqual("bar", traits.ToArray()[0].Value); }
public async Task IntT_InMem_AccessToken_Delete_ByContent() { await TestCase.AccessToken_Delete_ByContent().ConfigureAwait(false); }
private void testMultibyte(IMac mac, TestCase testCase) { mac.BlockUpdate(testCase.getAd(), 0, testCase.getAd().Length); checkMac(mac, testCase); }
public void InitializeTest() { this.dataCollectionSink = new InProcDataCollectionSink(); this.testCase = new TestCase("DummyNS.DummyC.DummyM", new Uri("executor://mstest/v1"), "Dummy.dll"); this.dataCollectionContext = new DataCollectionContext(this.testCase); }
public void SelectTestCase(TestCase testcase) { IsCurrent = false; this.testcase = testcase; SelectedCaseChanged(); }
public TestCaseSandbox(TestCase testCase, NPath rootTemporaryDirectory) : this(testCase, rootTemporaryDirectory, string.Empty) { }
public LtmTestCaseItem(TestCase item) : base(item) { }
public TestCaseSandbox(TestCase testCase, string rootTemporaryDirectory, string namePrefix) : this(testCase, rootTemporaryDirectory.ToNPath(), namePrefix) { }
private static void TestCase_OnExecutionComplete(TestCase testCase, TestCaseResult testCaseResult) { LogEvent.Info(message: $"Test case execution \"{testCase.Title}\" completed ({testCaseResult.TestVerdict})."); }
public void ExecuteSendPipelineWithDefaultXmlAsmWithImportedSchemaTest() { // Create test case... var tc = new TestCase { Name = "ExecuteSendPipelineWithDefaultXmlAsmWithImportedSchemaTest" }; var pipeStep = new ExecuteSendPipelineStep { PipelineAssemblyPath = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\bin\Debug\BizUnit.BizTalkTestArtifacts.dll", PipelineTypeName = "BizUnit.BizTalkTestArtifacts.SendPipeline1" }; var ds = new DocSpecDefinition { AssemblyPath = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\bin\Debug\BizUnit.BizTalkTestArtifacts.dll", TypeName = "BizUnit.BizTalkTestArtifacts.Schema0" }; pipeStep.DocSpecs.Add(ds); ds = new DocSpecDefinition { AssemblyPath = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\bin\Debug\BizUnit.BizTalkTestArtifacts.dll", TypeName = "BizUnit.BizTalkTestArtifacts.Schema3Env" }; pipeStep.DocSpecs.Add(ds); pipeStep.SourceDir = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\Instances\"; pipeStep.SearchPattern = "Child*.xml"; pipeStep.Destination = "Output.021.xml"; // Add ExecuteReceivePipelineStep to test case tc.ExecutionSteps.Add(pipeStep); var exists = new ExistsStep { DirectoryPath = ".", Timeout = 2000, SearchPattern = "Output.021*.xml", ExpectedNoOfFiles = 1 }; // Add ExistsStep to test case tc.ExecutionSteps.Add(exists); var fv = new FileReadMultipleStep { DirectoryPath = ".", SearchPattern = "Output.021.xml", DeleteFiles = false }; var validation = new XmlValidationStep(); var sd = new SchemaDefinition { XmlSchemaPath = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\Schema0.xsd", XmlSchemaNameSpace = "http://BizUnit.BizTalkTestArtifacts.Schema0" }; validation.XmlSchemas.Add(sd); sd = new SchemaDefinition { XmlSchemaPath = @"..\..\..\..\Test\BizUnit.BizTalkTestArtifacts\Schema3Env.xsd", XmlSchemaNameSpace = "http://BizUnit.BizTalkTestArtifacts.Schema3Env" }; validation.XmlSchemas.Add(sd); // Add validation to FileReadMultipleStep fv.SubSteps.Add(validation); // Add FileReadMultipleStep to test case tc.ExecutionSteps.Add(exists); TestCase.SaveToFile(tc, "ExecuteSendPipelineWithDefaultXmlAsmWithImportedSchemaTest.xaml"); // Execute test csse using serialised test case to test round tripping of serialisation... var bu = new BizUnit(TestCase.LoadFromFile("ExecuteSendPipelineWithDefaultXmlAsmWithImportedSchemaTest.xaml")); bu.RunTest(); }
public List <TestResult> CollectTestResults(IEnumerable <TestCase> testCasesRun, string testExecutable, string resultXmlFile, List <string> consoleOutput, TestCase crashedTestCase) { var testResults = new List <TestResult>(); TestCase[] arrTestCasesRun = testCasesRun as TestCase[] ?? testCasesRun.ToArray(); if (testResults.Count < arrTestCasesRun.Length) { CollectResultsFromXmlFile(arrTestCasesRun, testExecutable, resultXmlFile, testResults); } var consoleParser = new StandardOutputTestResultParser(arrTestCasesRun, consoleOutput, _logger); if (testResults.Count < arrTestCasesRun.Length) { CollectResultsFromConsoleOutput(consoleParser, testResults); } if (testResults.Count < arrTestCasesRun.Length) { if (crashedTestCase == null) { crashedTestCase = consoleParser.CrashedTestCase; } var remainingTestCases = arrTestCasesRun .Where(tc => !testResults.Exists(tr => tr.TestCase.FullyQualifiedName == tc.FullyQualifiedName)) .ToArray(); if (crashedTestCase != null) { CreateMissingResults(remainingTestCases, crashedTestCase, testResults); } else { ReportSuspiciousTestCases(remainingTestCases, testResults); } } return(testResults); }