private SessionManager GetSessionManager(TestScenario scenario)
        {
            var connectionFactoryMock = new Mock <IDbConnectionFactory>();
            var connectionMock        = new Mock <IDbConnection>();
            var commandMock           = new Mock <IDbCommand>();
            var paramsMock            = new Mock <IDataParameterCollection>();
            var paramMock             = new Mock <IDbDataParameter>();

            connectionFactoryMock.Setup(m => m.CreateConnection()).Returns(connectionMock.Object);
            connectionMock.Setup(m => m.CreateCommand()).Returns(commandMock.Object);
            commandMock.Setup(m => m.CreateParameter()).Returns(paramMock.Object);
            commandMock.SetupGet(m => m.Parameters).Returns(paramsMock.Object);

            switch (scenario)
            {
            case TestScenario.FAIL_BOOL_RETURN:
            case TestScenario.PASS_BOOL_RETURN:
                commandMock.Setup(m => m.ExecuteNonQuery()).Verifiable();
                paramMock.Setup(m => m.Value).Returns((int)scenario % 2);
                break;

            case TestScenario.FAIL_OBJECT_RETURN:
                break;

            case TestScenario.PASS_OBJECT_RETURN:
                var adapterMock   = new Mock <IDataAdapter>();
                var dataSetMock   = new Mock <DataSet>();
                var dataTableMock = new Mock <DataTable>();
                var dataRowMock   = new Mock <DataRow>();
                connectionFactoryMock.Setup(m => m.CreateDataAdapter(commandMock.Object)).Returns(adapterMock.Object);
                adapterMock.Setup(m => m.Fill(dataSetMock.Object));
                break;
            }

            return(new SessionManager(connectionFactoryMock.Object));
        }
        public async Task Batch_Double_Dispose_Response_Still_Available()
        {
            await using TestScenario scenario = Scenario();
            BlobClient[] blobs = await scenario.CreateBlobsAsync(3);

            BlobBatchClient client = scenario.GetBlobBatchClient();

            Response[] responses = new Response[3];
            Response   response;

            using (BlobBatch batch = client.CreateBatch())
            {
                responses[0] = batch.DeleteBlob(blobs[0].Uri);
                responses[1] = batch.DeleteBlob(blobs[1].Uri);
                responses[2] = batch.DeleteBlob(blobs[2].Uri);
                response     = await client.SubmitBatchAsync(batch);

                batch.Dispose();
                Assert.AreEqual(3, batch.RequestCount);
            }
            scenario.AssertStatus(202, response);
            scenario.AssertStatus(202, responses);
            await scenario.AssertDeleted(blobs);
        }
Esempio n. 3
0
        public async Task <IActionResult> OnGetAsync(string testScenarioId)
        {
            Guard.IsNullOrWhiteSpace(testScenarioId, nameof(testScenarioId));

            TestScenario scenario = await GetCurrentScenario(testScenarioId);

            if (scenario == null)
            {
                _logger.Warning("Test scenario response is null");
                return(new NotFoundObjectResult("Test Scenario not found"));
            }

            DoesUserHavePermissionToSave = (await _authorizationHelper.DoesUserHavePermission(User, scenario, SpecificationActionTypes.CanEditQaTests)).ToString().ToLowerInvariant();

            SpecificationSummary specResponse = await GetSpecification(scenario.SpecificationId);

            if (specResponse == null)
            {
                return(new PreconditionFailedResult("Specification not found"));
            }

            EditScenarioViewModel = new ScenarioEditViewModel
            {
                Name = JavaScriptEncoder.Default.Encode(scenario.Name),

                Gherkin = JavaScriptEncoder.Default.Encode(scenario.Gherkin),

                Description = JavaScriptEncoder.Default.Encode(scenario.Description)
            };

            TestScenarioId    = testScenarioId;
            SpecificationId   = scenario.SpecificationId;
            SpecificationName = specResponse.Name;

            return(Page());
        }
        private void RunTestScenarios(string scenarioName, RunContext runContext)
        {
            string tempFile = Path.GetTempFileName();

            try
            {
                string[] pathObjects = runContext.TestFeatures.Keys.ToArray();
                if (pathObjects.Length == 0)
                {
                    return;
                }

                _powerShell.AddCommand("Invoke-Gherkin")
                .AddParameter("Path", pathObjects)
                //.AddParameter("DetailedCodeCoverage")
                .AddParameter("CodeCoverageOutputFile", tempFile)
                .AddParameter("PassThru");
                if (!string.IsNullOrEmpty(scenarioName))
                {
                    _powerShell.AddParameter("ScenarioName", scenarioName);
                }

                string[] codecoverage = GetCodeCoverageFilenames(runContext, name => name.Substring(0, name.Length - Constant.TestsPs1.Length));
                if (codecoverage != null &&
                    codecoverage.Length > 0)
                {
                    _powerShell.AddParameter("CodeCoverage", codecoverage);
                }

                Collection <PSObject> pesterResults = _powerShell.Invoke();
                _powerShell.Commands.Clear();

                // The test results are not necessary stored in the first PSObject.
                Array results = GetTestResults(pesterResults);
                if (results.Length == 0)
                {
                    foreach (TestFeature file in runContext.TestFeatures.Values)
                    {
                        file.SetOutcome(TestOutcome.Failed);
                    }
                }
                else
                {
                    int          i            = 0;
                    TestScenario lastScenario = null;
                    foreach (PSObject result in results)
                    {
                        string filename = result.Properties["Filename"].Value as string;
                        string scenario = result.Properties["Describe"].Value as string;
                        if (filename != null &&
                            runContext.TestFeatures.TryGetValue(filename, out TestFeature feature))
                        {
                            TestScenario testScenario = feature.Scenarios.FirstOrDefault(s => s.Name == scenario);
                            if (testScenario != null)
                            {
                                if (lastScenario != testScenario)
                                {
                                    i            = 0;
                                    lastScenario = testScenario;
                                }
                                testScenario.ProcessTestResults(result, i);
                            }
                        }
                        i++;
                    }
                    Report report = Report.Load(tempFile);
                    if (report != null)
                    {
                        runContext.AddCodeCoverageReport(report);
                    }
                }
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
 public void OpenItemList()
 {
     // Open Customers
     TestScenario.Run(OrderProcessorUserContextManager, TestContext,
                      userContext => TestScenario.RunPageAction(TestContext, userContext, ItemListPageId));
 }
        public void Execute(TestScenario testScenario, TestScenarioResults testScenarioResults,
                            bool shouldExecuteRecordedRequestPauses, List <string> ignoreUrlRequestsPatterns)
        {
            var testScenarioRunResult = new TestScenarioRunResult();
            var watch = Stopwatch.StartNew();

            foreach (var httpRequestDto in testScenario.Requests)
            {
                if (ShouldFilterRequest(httpRequestDto.Url, ignoreUrlRequestsPatterns))
                {
                    continue;
                }

                var requestResults = new RequestResults();
                try
                {
                    if (shouldExecuteRecordedRequestPauses)
                    {
                        Thread.Sleep(httpRequestDto.MillisecondsPauseAfterPreviousRequest);
                    }


                    var request  = CreateRestRequest(httpRequestDto);
                    var response = ExecuteMeasuredRequest(request);

                    UpdateCookiesCollection(response);

                    requestResults.ExecutionTime = response.ExecutionTime;

                    requestResults.StatusCode   = response.StatusCode;
                    requestResults.RequestUrl   = response.ResponseUri.ToString();
                    requestResults.IsSuccessful = response.IsSuccessful;
                    if (!response.IsSuccessful)
                    {
                        requestResults.ResponseContent = response.ResponseUri.ToString();
                    }

                    foreach (var loadTestAssertionHandler in _loadTestAssertionHandlers)
                    {
                        var responseAssertionResults = loadTestAssertionHandler.Execute(httpRequestDto, response);
                        requestResults.ResponseAssertionResults.AddRange(responseAssertionResults);
                    }
                }
                catch (Exception ex)
                {
                    requestResults.RequestUrl      = httpRequestDto.Url;
                    requestResults.IsSuccessful    = false;
                    requestResults.ResponseContent = $"{httpRequestDto.Url} {ex.Message}";
                    Console.WriteLine($"FAILED- {httpRequestDto.Url}");
                }

                testScenarioRunResult.RequestResults.Add(requestResults);
            }

            watch.Stop();

            testScenarioRunResult.ExecutionTime = watch.Elapsed;
            testScenarioResults.TimesExecuted++;
            testScenarioResults.Weight = testScenario.Weight;
            if (testScenarioRunResult.Passed)
            {
                testScenarioResults.TimesPassed++;
            }
            else
            {
                testScenarioResults.TimesFailed++;
            }

            testScenarioResults.TestScenarioRunResults.GetOrAdd(testScenarioRunResult.RunId, testScenarioRunResult);
        }
Esempio n. 7
0
        /// <summary>
        /// Allows the demonstration of various scenarios using
        /// WorkflowApplication
        /// </summary>
        private static void BasicApplicationTest(TestScenario scenario)
        {
            AutoResetEvent waitEvent = new AutoResetEvent(false);

            WorkflowApplication wfApp = new WorkflowApplication(
                new HostingDemoWorkflow(),
                new Dictionary <String, Object>
            {
                { "ArgNumberToEcho", 1001 },
            });

            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                switch (e.CompletionState)
                {
                case ActivityInstanceState.Closed:
                    Console.WriteLine("Host: {0} Closed - Thread:{1} - {2}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId,
                                      e.Outputs["Result"]);
                    break;

                case ActivityInstanceState.Canceled:
                    Console.WriteLine("Host: {0} Canceled - Thread:{1}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId);
                    break;

                case ActivityInstanceState.Executing:
                    Console.WriteLine("Host: {0} Executing - Thread:{1}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId);
                    break;

                case ActivityInstanceState.Faulted:
                    Console.WriteLine(
                        "Host: {0} Faulted - Thread:{1} - {2}:{3}",
                        wfApp.Id,
                        System.Threading.Thread.CurrentThread.ManagedThreadId,
                        e.TerminationException.GetType(),
                        e.TerminationException.Message);
                    break;

                default:
                    break;
                }
                waitEvent.Set();
            };

            wfApp.OnUnhandledException =
                delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(
                    "Host: {0} OnUnhandledException - Thread:{1} - {2}",
                    wfApp.Id,
                    System.Threading.Thread.CurrentThread.ManagedThreadId,
                    e.UnhandledException.Message);
                waitEvent.Set();
                return(UnhandledExceptionAction.Cancel);
            };

            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine("Host: {0} Aborted - Thread:{1} - {2}:{3}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId,
                                  e.Reason.GetType(), e.Reason.Message);
                waitEvent.Set();
            };

            wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                Console.WriteLine("Host: {0} Idle - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
            };

            wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                Console.WriteLine("Host: {0} PersistableIdle - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
                return(PersistableIdleAction.Unload);
            };

            wfApp.Unloaded = delegate(WorkflowApplicationEventArgs e)
            {
                Console.WriteLine("Host: {0} Unloaded - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
            };

            try
            {
                Console.WriteLine("Host: About to run {0} - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);

                //determine the demonstration scenario
                switch (scenario)
                {
                case TestScenario.Normal:
                    wfApp.Run();
                    waitEvent.WaitOne();
                    break;

                //case TestScenario.TimeSpan:
                //    wfApp.Run(TimeSpan.FromSeconds(1));
                //    waitEvent.WaitOne();
                //    break;

                case TestScenario.Cancel:
                    wfApp.Run();
                    //Wait just a bit then cancel the workflow
                    Thread.Sleep(1000);
                    wfApp.Cancel();
                    waitEvent.WaitOne();
                    break;

                case TestScenario.Abort:
                    wfApp.Run();
                    //Wait just a bit then abort the workflow
                    Thread.Sleep(1000);
                    wfApp.Abort("My aborted reason");
                    waitEvent.WaitOne();
                    break;

                case TestScenario.Terminate:
                    wfApp.Run();
                    //Wait just a bit then terminate the workflow
                    Thread.Sleep(1000);
                    wfApp.Terminate("My termination reason");
                    waitEvent.WaitOne();
                    break;

                case TestScenario.BeginRun:
                    wfApp.BeginRun(delegate(IAsyncResult ar)
                    {
                        Console.WriteLine(
                            "Host: {0} BeginRunCallback - Thread:{1}",
                            wfApp.Id,
                            System.Threading.Thread.CurrentThread.ManagedThreadId);
                        ((WorkflowApplication)ar.AsyncState).EndRun(ar);
                    }, wfApp);
                    waitEvent.WaitOne();
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Host: {0} exception:{1}:{2}",
                                  wfApp.Id, exception.GetType(), exception.Message);
            }
        }
 public async Task ManyManyConcatenatedGzipStreams(int streamCount, TestScenario scenario, int bufferSize, int bytesPerStream)
 {
     await TestConcatenatedGzipStreams(streamCount, scenario, bufferSize, bytesPerStream);
 }
Esempio n. 9
0
        public async Task <IActionResult> SaveVersion(HttpRequest request)
        {
            string json = await request.GetRawBodyStringAsync();

            CreateNewTestScenarioVersion scenarioVersion = JsonConvert.DeserializeObject <CreateNewTestScenarioVersion>(json);

            if (scenarioVersion == null)
            {
                _logger.Error("A null scenario version was provided");

                return(new BadRequestObjectResult("Null or empty calculation Id provided"));
            }

            BadRequestObjectResult validationResult = (await _createNewTestScenarioVersionValidator.ValidateAsync(scenarioVersion)).PopulateModelState();

            if (validationResult != null)
            {
                return(validationResult);
            }

            TestScenario testScenario = null;

            if (!string.IsNullOrEmpty(scenarioVersion.Id))
            {
                testScenario = await _scenariosRepository.GetTestScenarioById(scenarioVersion.Id);
            }

            bool saveAsVersion = true;

            SpecificationSummary specification = await _specificationsRepository.GetSpecificationSummaryById(scenarioVersion.SpecificationId);

            if (specification == null)
            {
                _logger.Error($"Unable to find a specification for specification id : {scenarioVersion.SpecificationId}");

                return(new StatusCodeResult(412));
            }

            Reference user = request.GetUserOrDefault();

            if (testScenario == null)
            {
                string Id = Guid.NewGuid().ToString();

                testScenario = new TestScenario
                {
                    Id = Id,
                    SpecificationId = specification.Id,
                    Name            = scenarioVersion.Name,
                    Current         = new TestScenarioVersion
                    {
                        Date             = DateTimeOffset.Now.ToLocalTime(),
                        TestScenarioId   = Id,
                        PublishStatus    = PublishStatus.Draft,
                        Version          = 1,
                        Author           = user,
                        Gherkin          = scenarioVersion.Scenario,
                        Description      = scenarioVersion.Description,
                        FundingPeriodId  = specification.FundingPeriod.Id,
                        FundingStreamIds = specification.FundingStreams.Select(s => s.Id).ToArraySafe(),
                    }
                };
            }
            else
            {
                testScenario.Name = scenarioVersion.Name;

                saveAsVersion = !string.Equals(scenarioVersion.Scenario, testScenario.Current.Gherkin) ||
                                scenarioVersion.Description != testScenario.Current.Description;

                TestScenarioVersion newVersion = testScenario.Current.Clone() as TestScenarioVersion;

                if (saveAsVersion == true)
                {
                    newVersion.Author           = user;
                    newVersion.Gherkin          = scenarioVersion.Scenario;
                    newVersion.Description      = scenarioVersion.Description;
                    newVersion.FundingStreamIds = specification.FundingStreams.Select(s => s.Id).ToArraySafe();
                    newVersion.FundingPeriodId  = specification.FundingPeriod.Id;

                    newVersion = await _versionRepository.CreateVersion(newVersion, testScenario.Current);

                    testScenario.Current = newVersion;
                }
            }

            HttpStatusCode statusCode = await _scenariosRepository.SaveTestScenario(testScenario);

            if (!statusCode.IsSuccess())
            {
                _logger.Error($"Failed to save test scenario with status code: {statusCode.ToString()}");

                return(new StatusCodeResult((int)statusCode));
            }

            await _versionRepository.SaveVersion(testScenario.Current);

            ScenarioIndex scenarioIndex = CreateScenarioIndexFromScenario(testScenario, specification);

            await _searchRepository.Index(new List <ScenarioIndex> {
                scenarioIndex
            });

            await _cacheProvider.RemoveAsync <List <TestScenario> >($"{CacheKeys.TestScenarios}{testScenario.SpecificationId}");

            await _cacheProvider.RemoveAsync <GherkinParseResult>($"{CacheKeys.GherkinParseResult}{testScenario.Id}");

            IEnumerable <Models.Calcs.CalculationCurrentVersion> calculations = await _calcsRepositoryPolicy.ExecuteAsync(() => _calcsRepository.GetCurrentCalculationsBySpecificationId(specification.Id));

            if (calculations.IsNullOrEmpty())
            {
                _logger.Information($"No calculations found to test for specification id: '{specification.Id}'");
            }
            else
            {
                string correlationId = request.GetCorrelationId();

                try
                {
                    Trigger trigger = new Trigger
                    {
                        EntityId   = testScenario.Id,
                        EntityType = nameof(TestScenario),
                        Message    = $"Saving test scenario: '{testScenario.Id}'"
                    };

                    bool generateCalculationAggregations = SourceCodeHelpers.HasCalculationAggregateFunctionParameters(calculations.Select(m => m.SourceCode));

                    Job job = await SendInstructAllocationsToJobService(specification.Id, user, trigger, correlationId, generateCalculationAggregations);

                    _logger.Information($"New job of type '{job.JobDefinitionId}' created with id: '{job.Id}'");
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, $"Failed to create job of type '{JobConstants.DefinitionNames.CreateInstructAllocationJob}' on specification '{specification.Id}'");

                    return(new InternalServerErrorResult($"An error occurred attempting to execute calculations prior to running tests on specification '{specification.Id}'"));
                }
            }

            CurrentTestScenario testScenarioResult = await _scenariosRepository.GetCurrentTestScenarioById(testScenario.Id);

            return(new OkObjectResult(testScenarioResult));
        }
Esempio n. 10
0
        static string AppendSuffixToConstrainedType(TestScenario scenario, string constrainedType, out bool invalidScenario)
        {
            invalidScenario = false;
            switch (scenario.ConstrainedType)
            {
            case ConstrainedTypeScenario.NonGeneric:
                if (constrainedType.StartsWith(ImplPrefix + "Generic"))
                {
                    invalidScenario = true;
                }

                break;

            case ConstrainedTypeScenario.GenericOverTypeParameter:
                if (!constrainedType.StartsWith(ImplPrefix + "Generic"))
                {
                    invalidScenario = true;
                }
                if (scenario.CallerScenario == CallerMethodScenario.NonGeneric)
                {
                    invalidScenario = true;
                }
                if (scenario.CallerScenario == CallerMethodScenario.GenericOverConstrainedType)
                {
                    invalidScenario = true;
                }

                constrainedType = constrainedType + "<!!0>";
                break;

            case ConstrainedTypeScenario.GenericOverStruct:
                if (!constrainedType.StartsWith(ImplPrefix + "Generic"))
                {
                    invalidScenario = true;
                }
                constrainedType = constrainedType + "<int32>";
                break;

            case ConstrainedTypeScenario.GenericOverReferenceType_ClassA:
                if (!constrainedType.StartsWith(ImplPrefix + "Generic"))
                {
                    invalidScenario = true;
                }
                constrainedType = constrainedType + "<object>";
                break;

            case ConstrainedTypeScenario.GenericOverGenericStructOverTypeParameter:
                if (!constrainedType.StartsWith(ImplPrefix + "Generic"))
                {
                    invalidScenario = true;
                }
                if (scenario.CallerScenario == CallerMethodScenario.NonGeneric)
                {
                    invalidScenario = true;
                }
                if (scenario.CallerScenario == CallerMethodScenario.GenericOverConstrainedType)
                {
                    invalidScenario = true;
                }
                constrainedType = constrainedType + $"<valuetype {CommonPrefix}GenericStruct`1<!!0>>";
                break;

            default:
                throw new Exception("Unexpected value");
            }

            return(constrainedType);
        }
        private async Task ExecuteTestCase(TestScenario scenario)
        {
            TestScenarioExpectations expected =
                this.cosmosClient.ClientOptions.ConnectionMode == ConnectionMode.Gateway ?
                scenario.Gateway : scenario.Direct;

            Console.WriteLine($"Scenario: {scenario.Name}, Id: \"{scenario.Id}\"");

            ResponseMessage response = await this.Container.CreateItemStreamAsync(
                await CreateItemPayload(scenario.Id),
                new PartitionKey(scenario.Id));

            Assert.AreEqual(expected.ExpectedCreateStatusCode, response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                await DeserializeAndValidatePayload(response.Content, scenario.Id);
            }

            if (!expected.ExpectedCreateStatusCode.IsSuccess())
            {
                return;
            }

            response = await this.Container.ReadItemStreamAsync(
                scenario.Id,
                new PartitionKey(scenario.Id));

            Assert.AreEqual(expected.ExpectedReadStatusCode, response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                await DeserializeAndValidatePayload(response.Content, scenario.Id);
            }

            response = await this.Container.ReplaceItemStreamAsync(
                await CreateItemPayload(scenario.Id),
                scenario.Id,
                new PartitionKey(scenario.Id));

            Assert.AreEqual(expected.ExpectedReplaceStatusCode, response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                await DeserializeAndValidatePayload(response.Content, scenario.Id);
            }

            response = await this.Container.DeleteItemStreamAsync(
                scenario.Id,
                new PartitionKey(scenario.Id));

            Assert.AreEqual(expected.ExpectedDeleteStatusCode, response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                if (this.cosmosClient.ClientOptions.ConnectionMode == ConnectionMode.Gateway)
                {
                    await ValidateEmptyPayload(response.Content);
                }
                else
                {
                    Assert.IsNull(response.Content);
                }
            }
        }
        private void CompleteLastLayer()
        {
            // Step 1: Get edges with the color of the top face
            IEnumerable <Cube> topCorners =
                Rubik.Cubes
                .Where(c => c.IsCorner)
                .Where(c => c.Position.HasFlag(CubeFlag.TopLayer));

            // Step 2: Bring corners to their target position
            while (topCorners.Count(c => c.Position.Flags == GetTargetFlags(c)) < 4)
            {
                var correctCorners = topCorners.Where(c => c.Position.Flags == GetTargetFlags(c));

                CubeFlag rightSlice;
                if (correctCorners.Count() != 0)
                {
                    Cube firstCube = correctCorners.First();
                    Face rightFace = firstCube.Faces.First(f => f.Color != Color.Black && f.Position != FacePosition.Top);

                    rightSlice = CubeFlagService.FromFacePosition(rightFace.Position);

                    if (!new TestScenario(Rubik, new LayerMove(rightSlice, true, false)).TestCubePosition(firstCube, CubeFlag.TopLayer))
                    {
                        rightSlice =
                            CubeFlagService.FromFacePosition(
                                firstCube.Faces
                                .First(f =>
                                       f.Color != rightFace.Color &&
                                       f.Color != Color.Black &&
                                       f.Position != FacePosition.Top
                                       ).Position
                                );
                    }
                }
                else
                {
                    rightSlice = CubeFlag.RightSlice;
                }

                SolverAlgorithm(
                    "U {0} U' {1}' U {0}' U' {1}",
                    CubeFlagService.ToNotationString(rightSlice),
                    CubeFlagService.ToNotationString(CubeFlagService.GetOppositeFlag(rightSlice))
                    );
            }

            // Step 3: Orientation of the corners on the top layer
            Face rightFac = topCorners.First().Faces.First(f => f.Color != Color.Black && f.Position != FacePosition.Top);

            var scenario       = new TestScenario(this.Rubik, new LayerMove(CubeFlagService.FromFacePosition(rightFac.Position), true, false));
            var scenarioPassed = scenario.TestCubePosition(topCorners.First(), CubeFlag.TopLayer);

            var positionForRightSlic =
                !scenarioPassed
                    ? rightFac.Position
                    : topCorners.First().Faces.First(f => f.Color != rightFac.Color && f.Color != Color.Black && f.Position != FacePosition.Top).Position;

            CubeFlag rightSlic = CubeFlagService.FromFacePosition(positionForRightSlic);



            foreach (Cube c in topCorners)
            {
                while (!c.Position.HasFlag(rightSlic))
                {
                    SolverMove(CubeFlag.TopLayer, true);
                }

                if (!new TestScenario(Rubik, new LayerMove(rightSlic, true, false)).TestCubePosition(c, CubeFlag.TopLayer))
                {
                    SolverMove(CubeFlag.TopLayer, true);
                }

                // Algorithm: R' D' R D
                while (c.Faces.First(f => f.Position == FacePosition.Top).Color != Rubik.TopColor)
                {
                    SolverAlgorithm("{0}' D' {0} D", CubeFlagService.ToNotationString(rightSlic));
                }
            }

            while (topCorners.Count(tC => tC.Position.Flags == GetTargetFlags(tC)) != 4)
            {
                SolverMove(CubeFlag.TopLayer, true);
            }
        }
Esempio n. 13
0
 public void Post([FromBody] TestScenario value)
 {
     _testScenarioRepository.InsertAsync(value);
 }
Esempio n. 14
0
        public IActionResult Get(int id)
        {
            TestScenario res = _testScenarioRepository.GetAsync(id).Result;

            return(Ok(res));
        }
        private void SetupPasswordHasher(TestScenario testScenario)
        {
            if (testScenario == TestScenario.RegisterUserSuccess)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.RegisterUserPasswordGenerateFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns(String.Empty);
            }

            if (testScenario == TestScenario.RegisterUserCreateUserFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.RegisterUserAddRolesFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.RegisterUserAddRolesFailedDeleteFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.RegisterUserAddClaimsFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.RegisterUserAddClaimsFailedDeleteFailed)
            {
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.ChangePasswordSuccess)
            {
                this.PasswordHasher
                .Setup(ph =>
                       ph.VerifyHashedPassword(It.IsAny <IdentityUser>(), It.IsAny <String>(), It.IsAny <String>()))
                .Returns(PasswordVerificationResult.Success);
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.ResetPasswordSuccess)
            {
                this.PasswordHasher
                .Setup(ph =>
                       ph.VerifyHashedPassword(It.IsAny <IdentityUser>(), It.IsAny <String>(), It.IsAny <String>()))
                .Returns(PasswordVerificationResult.Success);
                this.PasswordHasher.Setup(ph => ph.HashPassword(It.IsAny <IdentityUser>(), It.IsAny <String>()))
                .Returns("HashedPassword");
            }

            if (testScenario == TestScenario.ChangePasswordOldPasswordIncorrect)
            {
                this.PasswordHasher
                .Setup(ph =>
                       ph.VerifyHashedPassword(It.IsAny <IdentityUser>(), It.IsAny <String>(), It.IsAny <String>()))
                .Returns(PasswordVerificationResult.Failed);
            }
        }
        protected static TestFeature DiscoverPesterFeatures(string source, IMessageLogger logger)
        {
            if (!File.Exists(source))
            {
                return(null);
            }

            Gherkin.Parser parser = new Gherkin.Parser();

            GherkinDocument document = parser.Parse(source);

            TestFeature feature = new TestFeature
            {
                Name     = Path.GetFileNameWithoutExtension(source),
                Path     = source,
                Document = document
            };

            foreach (ScenarioDefinition scenario in document.Feature.Children)
            {
                if (scenario is ScenarioOutline outline)
                {
                    foreach (Examples example in outline.Examples)
                    {
                        TestScenario testScenario = new TestScenario()
                        {
                            Name     = $"{scenario.Name}\n  Examples:{example.Name}",
                            Path     = source,
                            Scenario = scenario
                        };
                        feature.Scenarios.Add(testScenario);
                        foreach (TableRow row in example.TableBody)
                        {
                            foreach (Step step in scenario.Steps)
                            {
                                TestStep testStep = new TestStep()
                                {
                                    Name = step.Text,
                                    Path = source,
                                    Step = step
                                };
                                testScenario.Steps.Add(testStep);
                            }
                        }
                    }
                }
                else
                {
                    TestScenario testScenario = new TestScenario()
                    {
                        Name     = scenario.Name,
                        Path     = source,
                        Scenario = scenario
                    };

                    feature.Scenarios.Add(testScenario);

                    foreach (Step step in scenario.Steps)
                    {
                        TestStep testStep = new TestStep()
                        {
                            Name = step.Text,
                            Path = source,
                            Step = step
                        };
                        testScenario.Steps.Add(testStep);
                    }
                }
            }
            if (feature.Scenarios.Count == 0)
            {
                return(null);
            }
            return(feature);
        }
Esempio n. 17
0
 List<ITestScenario> ImportTestScenarios(IEnumerable<XElement> scenarioElements, string suiteId, Guid suiteUniqueId)
 {
     var importedTestScenarios = new List<ITestScenario>();
     if (null == scenarioElements) return importedTestScenarios;
     
     foreach (var scenarioElement in scenarioElements) {
         var scenarioDescription = string.Empty;
         scenarioDescription = GetStringAttribute(scenarioElement, "description");
         
         var addTestScenario = false;
         var testScenario = importedTestScenarios.FirstOrDefault(tsc => tsc.Id == GetStringAttribute(scenarioElement, "id") &&
                                                        tsc.Name == GetStringAttribute(scenarioElement, "name") &&
                                                        tsc.PlatformUniqueId == GetGuidAttribute(scenarioElement, "platformUniqueId"));
         
         if (null == testScenario) {
             testScenario = new TestScenario {
                 UniqueId = GetGuidAttribute(scenarioElement, "uniqueId"),
                 Id = GetStringAttribute(scenarioElement, "id"),
                 Name = GetStringAttribute(scenarioElement, "name"),
                 PlatformId = GetStringAttribute(scenarioElement, "platformId"),
                 PlatformUniqueId = GetGuidAttribute(scenarioElement, "platformUniqueId"),
                 Description = scenarioDescription,
                 TimeSpent = GetDoubleAttribute(scenarioElement, "timeSpent"),
                 SuiteId = suiteId,
                 SuiteUniqueId = suiteUniqueId
             };
             addTestScenario = true;
         }
         var testResultElements = from testResultElement in scenarioElement.Descendants("testResult")
             where testScenario.PlatformUniqueId == GetGuidAttribute(testResultElement, "platformUniqueId")
                           //where testResult.Attribute("name").Value != "autoclosed"
         select testResultElement;
         testScenario.TestResults.AddRange(ImportTestResults(testResultElements, testScenario.SuiteId, testScenario.SuiteUniqueId, testScenario.Id, testScenario.UniqueId));
         if (addTestScenario)
             importedTestScenarios.Add(testScenario);
     }
     return importedTestScenarios;
 }
Esempio n. 18
0
        static void Main(string[] args)
        {
            using StreamWriter twOutputCommon = new StreamWriter(Path.Combine(args[0], @$ "{CommonAndImplAssemblyName}.il"));
            using StreamWriter twOutputTest   = new StreamWriter(Path.Combine(args[0], @$ "{TestAssemblyName}.il"));

            StringWriter swMainMethodBody   = new StringWriter();
            StringWriter swTestClassMethods = new StringWriter();

            EmitTestGlobalHeader(twOutputCommon);
            EmitAssemblyRecord(twOutputCommon, CommonAndImplAssemblyName);
            EmitCodeForCommonLibrary(twOutputCommon);
            GenerateImplementations(twOutputCommon);

            EmitTestGlobalHeader(twOutputTest);
            EmitAssemblyExternRecord(twOutputTest, CommonAndImplAssemblyName);
            EmitAssemblyRecord(twOutputTest, TestAssemblyName);

            foreach (var scenario in TestScenario.GetScenarios())
            {
                string scenarioName = scenario.ToString();

                string constrainedType = AppendSuffixToConstrainedType(scenario, GetConstrainedTypeName(scenario.ConstrainedTypeDefinition), out bool skipScenario);
                if (skipScenario)
                {
                    continue;
                }

                string interfaceTypeSansImplPrefix;
                string interfaceMethod;

                string constrainedTypePrefix;
                if (constrainedType.Contains("Valuetype"))
                {
                    constrainedTypePrefix = $"valuetype ";
                }
                else
                {
                    constrainedTypePrefix = $"class ";
                }

                switch (scenario.InterfaceType)
                {
                case InterfaceType.NonGeneric:
                    interfaceTypeSansImplPrefix = "IFaceNonGeneric";
                    break;

                case InterfaceType.GenericOverString:
                    if (scenario.CallerScenario == CallerMethodScenario.GenericOverConstrainedType)
                    {
                        interfaceTypeSansImplPrefix = "IFaceGeneric`1<!!1>";
                    }
                    else
                    {
                        interfaceTypeSansImplPrefix = "IFaceGeneric`1<string>";
                    }
                    break;

                case InterfaceType.GenericOverObject:
                    if (scenario.CallerScenario == CallerMethodScenario.GenericOverConstrainedType)
                    {
                        interfaceTypeSansImplPrefix = "IFaceGeneric`1<!!1>";
                    }
                    else
                    {
                        interfaceTypeSansImplPrefix = "IFaceGeneric`1<object>";
                    }
                    break;

                case InterfaceType.CuriouslyRecurringGeneric:
                    interfaceTypeSansImplPrefix = $"IFaceCuriouslyRecurringGeneric`1<{constrainedTypePrefix}{constrainedType}>";
                    break;

                default:
                    throw new Exception("Unexpected value");
                }

                string interfaceMethodRoot;
                string interfaceMethodInstantiation = "";

                switch (scenario.MethodType)
                {
                case MethodType.NormalMethod:
                    interfaceMethodRoot = "NormalMethod";
                    break;

                case MethodType.GenericMethodOverInt:
                    interfaceMethodRoot          = "GenericMethod";
                    interfaceMethodInstantiation = "<int32>";
                    break;

                case MethodType.GenericMethodOverString:
                    interfaceMethodRoot          = "GenericMethod";
                    interfaceMethodInstantiation = "<string>";
                    break;

                case MethodType.GenericMethodOverTypeParameter:
                    interfaceMethodRoot = "GenericMethod";
                    if (scenario.CallerScenario == CallerMethodScenario.NonGeneric)
                    {
                        continue;
                    }
                    interfaceMethodInstantiation = "<!!0>";
                    break;

                default:
                    throw new Exception("Unexpected");
                }

                interfaceMethod = interfaceMethodRoot + interfaceMethodInstantiation;

                TextWriter twIL;

                MethodDesc mdIndividualTestMethod = new MethodDesc();
                string     basicTestMethodName    = $"Test_{scenarioName}";
                mdIndividualTestMethod.Name        = basicTestMethodName;
                mdIndividualTestMethod.HasBody     = true;
                mdIndividualTestMethod.MethodFlags = "public static";
                mdIndividualTestMethod.MethodImpls = null;
                mdIndividualTestMethod.ReturnType  = "void";
                mdIndividualTestMethod.Arguments   = "";


                string expectedString = constrainedTypePrefix + AppendSuffixToConstrainedType(scenario, GetConstrainedTypeName(scenario.ConstrainedTypeDefinition, withImplPrefix: false), out _) + "'" + interfaceTypeSansImplPrefix + "." + interfaceMethodRoot + "'" + interfaceMethodInstantiation;
                expectedString = expectedString.Replace(ImplPrefix, "");

                if (scenario.CallerScenario == CallerMethodScenario.NonGeneric)
                {
                    EmitTestMethod();
                    CallTestEntrypoint($"        call void TestEntrypoint::{mdIndividualTestMethod.Name}()");
                }
                else
                {
                    string methodInstantiation;
                    switch (scenario.CallerScenario)
                    {
                    case CallerMethodScenario.GenericOverInt32:
                    case CallerMethodScenario.GenericOverString:

                        mdIndividualTestMethod.Name = mdIndividualTestMethod.Name + "<T>";
                        methodInstantiation         = "string";
                        if (scenario.CallerScenario == CallerMethodScenario.GenericOverInt32)
                        {
                            methodInstantiation = "int32";
                        }

                        expectedString = expectedString.Replace("!!0", $"{methodInstantiation}");
                        expectedString = expectedString.Replace(ImplPrefix, "");
                        EmitTestMethod();

                        CallTestEntrypoint($"        call void TestEntrypoint::{basicTestMethodName}<{methodInstantiation}>()");
                        break;

                    case CallerMethodScenario.GenericOverConstrainedType:
                        mdIndividualTestMethod.Name = $"{mdIndividualTestMethod.Name}<({(interfaceTypeSansImplPrefix.Contains("`") ? "class " : "")}{CommonPrefix}{interfaceTypeSansImplPrefix}) T,U>";

                        expectedString = expectedString.Replace("!!0", $"{constrainedTypePrefix}{constrainedType}");
                        expectedString = expectedString.Replace(ImplPrefix, "");

                        EmitTestMethod();

                        string callCommand = GetSetBangBang1IfNeeded("string") + $"    call void TestEntrypoint::{basicTestMethodName}<{constrainedTypePrefix}{constrainedType},string>()";
                        if (scenario.InterfaceType == InterfaceType.GenericOverObject)
                        {
                            callCommand = callCommand + Environment.NewLine + GetSetBangBang1IfNeeded("object") + $"        call void TestEntrypoint::{basicTestMethodName}<{constrainedTypePrefix}{constrainedType},object>()";
                        }
                        CallTestEntrypoint(callCommand);

                        string GetSetBangBang1IfNeeded(string bangBang1Expected)
                        {
                            if (expectedString.Contains("!!1"))
                            {
                                return($"    ldstr \"{bangBang1Expected}\"" + Environment.NewLine + "    stsfld string [GenericContextCommonCs]Statics::BangBang1Param" + Environment.NewLine);
                            }
                            else
                            {
                                return("");
                            }
                        }

                        break;

                    default:
                        throw new Exception("AACLL");
                    }
                }

                void CallTestEntrypoint(string callCommand)
                {
                    swMainMethodBody.WriteLine("    .try {");
                    swMainMethodBody.WriteLine(callCommand);
                    swMainMethodBody.WriteLine($"        leave.s {scenarioName}Done");
                    swMainMethodBody.WriteLine("    } catch [System.Runtime]System.Exception {");
                    swMainMethodBody.WriteLine($"        stloc.0");
                    swMainMethodBody.WriteLine($"        ldstr \"{scenarioName}\"");
                    swMainMethodBody.WriteLine($"        ldstr \"{expectedString}\"");
                    swMainMethodBody.WriteLine($"        ldloc.0");
                    swMainMethodBody.WriteLine($"        callvirt   instance string [System.Runtime]System.Object::ToString()");
                    swMainMethodBody.WriteLine($"        call void [GenericContextCommonCs]Statics::CheckForFailure(string,string,string)");
                    swMainMethodBody.WriteLine($"        leave.s {scenarioName}Done");
                    swMainMethodBody.WriteLine("    }");
                    swMainMethodBody.WriteLine($"{scenarioName}Done: nop");
                }

                // If test scenario requires generic class caller, Create Caller class and make a global method method which calls it
                // If test scenario requires generic method caller, create global generic method as required and non-generic test method
                // If test scenario requires non-generic method caller, just make global method as caller
                //   Call callee
                //
                // Create Callee class
                //   With callee method that implements scenario
                //   fill expected value static with string computed based on scenario + exact type of calle class/generic args of callee method
                // compute expected result string

                void EmitTestMethod()
                {
                    EmitMethod(swTestClassMethods, mdIndividualTestMethod);
                    EmitILToCallActualMethod(swTestClassMethods);
                    swTestClassMethods.WriteLine($"    ldstr \"{scenario.ToString()}\"");
                    swTestClassMethods.WriteLine($"    ldstr \"{expectedString}\"");
                    if (expectedString.Contains("!!1"))
                    {
                        swTestClassMethods.WriteLine("    ldstr \"!!1\"");
                        swTestClassMethods.WriteLine("    ldsfld string [GenericContextCommonCs]Statics::BangBang1Param");
                        swTestClassMethods.WriteLine("    call instance string [System.Runtime]System.String::Replace(string, string)");
                    }
                    swTestClassMethods.WriteLine($"    call void {CommonCsPrefix}Statics::CheckForFailure(string,string)");
                    swTestClassMethods.WriteLine($"    ret");
                    twIL = swTestClassMethods;
                    EmitEndMethod(swTestClassMethods, mdIndividualTestMethod);
                }

                void EmitILToCallActualMethod(TextWriter twActualIL)
                {
                    // Emit the IL to call the actual method
                    switch (scenario.Operation)
                    {
                    case OperationTested.Call:
                        EmitConstrainedPrefix();
                        twActualIL.WriteLine($"    call void class {ImplPrefix}{interfaceTypeSansImplPrefix}::{interfaceMethod}()");
                        break;

                    case OperationTested.Ldftn:
                        EmitConstrainedPrefix();
                        twActualIL.WriteLine($"    ldftn void class {ImplPrefix}{interfaceTypeSansImplPrefix}::{interfaceMethod}()");
                        twActualIL.WriteLine($"    volatile.");
                        twActualIL.WriteLine($"    stsfld     native int modreq([System.Runtime]System.Runtime.CompilerServices.IsVolatile) {CommonCsPrefix}Statics::FtnHolder");
                        twActualIL.WriteLine($"    volatile.");
                        twActualIL.WriteLine($"    ldsfld     native int modreq([System.Runtime]System.Runtime.CompilerServices.IsVolatile) {CommonCsPrefix}Statics::FtnHolder");
                        twActualIL.WriteLine($"    calli      void()");
                        break;

                    case OperationTested.CreateDelegate:
                        twActualIL.WriteLine("    ldnull");
                        EmitConstrainedPrefix();
                        twActualIL.WriteLine($"    ldftn void class {ImplPrefix}{interfaceTypeSansImplPrefix}::{interfaceMethod}()");
                        twActualIL.WriteLine($"    newobj instance void [System.Runtime]System.Action::.ctor(object,");
                        twActualIL.WriteLine($"                                                              native int)");
                        twActualIL.WriteLine($"    volatile.");
                        twActualIL.WriteLine($"    stsfld     class [System.Runtime] System.Action modreq([System.Runtime] System.Runtime.CompilerServices.IsVolatile) {CommonCsPrefix}Statics::ActionHolder");
                        twActualIL.WriteLine($"    volatile.");
                        twActualIL.WriteLine($"    ldsfld class [System.Runtime] System.Action modreq([System.Runtime] System.Runtime.CompilerServices.IsVolatile) {CommonCsPrefix}Statics::ActionHolder");
                        twActualIL.WriteLine($"    callvirt instance void[System.Runtime] System.Action::Invoke()");
                        break;

                    default:
                        throw new Exception();
                    }

                    void EmitConstrainedPrefix()
                    {
                        if (scenario.CallerScenario == CallerMethodScenario.GenericOverConstrainedType)
                        {
                            twActualIL.WriteLine($"    constrained. !!0");
                        }
                        else
                        {
                            twActualIL.WriteLine($"    constrained. {constrainedTypePrefix}{constrainedType}");
                        }
                    }
                }
            }

            ClassDesc mainClass = new ClassDesc();

            mainClass.BaseType   = "[System.Runtime]System.Object";
            mainClass.ClassFlags = "public auto ansi";
            mainClass.Name       = "TestEntrypoint";

            EmitClass(twOutputTest, mainClass);

            twOutputTest.Write(swTestClassMethods.ToString());

            MethodDesc mainMethod = new MethodDesc();

            mainMethod.Name        = "Main";
            mainMethod.Arguments   = "";
            mainMethod.ReturnType  = "int32";
            mainMethod.MethodImpls = null;
            mainMethod.HasBody     = true;
            mainMethod.MethodFlags = "public static";

            EmitMethod(twOutputTest, mainMethod);
            twOutputTest.WriteLine("    .entrypoint");
            twOutputTest.WriteLine("    .locals init (class [System.Runtime]System.Exception V_0)");
            twOutputTest.Write(swMainMethodBody.ToString());
            twOutputTest.WriteLine($"    call int32 { CommonCsPrefix}Statics::ReportResults()");
            twOutputTest.WriteLine("    ret");

            EmitEndMethod(twOutputTest, mainMethod);
            EmitEndClass(twOutputTest, mainClass);
        }
 public void When_using_yaml_file_as_test_case_source_should_generate_test_cases(TestScenario scenario)
 {
     RunScenario(scenario);
 }
Esempio n. 20
0
 public ScenarioChangedEventArgs(TestScenario scenario)
 {
     this.scenario = scenario;
 }
        public async Task StreamTruncation_IsDetected(TestScenario scenario)
        {
            var buffer = new byte[16];

            byte[] source = Enumerable.Range(0, 64).Select(i => (byte)i).ToArray();
            byte[] compressedData;
            using (var compressed = new MemoryStream())
                using (Stream compressor = CreateStream(compressed, CompressionMode.Compress))
                {
                    foreach (byte b in source)
                    {
                        compressor.WriteByte(b);
                    }

                    compressor.Dispose();
                    compressedData = compressed.ToArray();
                }

            for (var i = 1; i <= compressedData.Length; i += 1)
            {
                bool expectException = i < compressedData.Length;
                using (var compressedStream = new MemoryStream(compressedData.Take(i).ToArray()))
                {
                    using (Stream decompressor = CreateStream(compressedStream, CompressionMode.Decompress))
                    {
                        var decompressedStream = new MemoryStream();

                        try
                        {
                            switch (scenario)
                            {
                            case TestScenario.Copy:
                                decompressor.CopyTo(decompressedStream);
                                break;

                            case TestScenario.CopyAsync:
                                await decompressor.CopyToAsync(decompressedStream);

                                break;

                            case TestScenario.Read:
                                while (ZipFileTestBase.ReadAllBytes(decompressor, buffer, 0, buffer.Length) != 0)
                                {
                                }
                                ;
                                break;

                            case TestScenario.ReadAsync:
                                while (await ZipFileTestBase.ReadAllBytesAsync(decompressor, buffer, 0, buffer.Length) != 0)
                                {
                                }
                                ;
                                break;

                            case TestScenario.ReadByte:
                                while (decompressor.ReadByte() != -1)
                                {
                                }
                                break;

                            case TestScenario.ReadByteAsync:
                                while (await decompressor.ReadByteAsync() != -1)
                                {
                                }
                                break;
                            }
                        }
                        catch (InvalidDataException e)
                        {
                            if (expectException)
                            {
                                continue;
                            }

                            throw new XunitException($"An unexpected error occurred while decompressing data:{e}");
                        }

                        if (expectException)
                        {
                            throw new XunitException($"Truncated stream was decompressed successfully but exception was expected: length={i}/{compressedData.Length}");
                        }
                    }
                }
            }
        }
        private async Task TestConcatenatedGzipStreams(int streamCount, TestScenario scenario, int bufferSize, int bytesPerStream = 1)
        {
            bool isCopy = scenario == TestScenario.Copy || scenario == TestScenario.CopyAsync;

            using (MemoryStream correctDecompressedOutput = new MemoryStream())
                // For copy scenarios use a derived MemoryStream to avoid MemoryStream's Copy optimization
                // that turns the Copy into a single Write passing the backing buffer
                using (MemoryStream compressedStream = isCopy ? new DerivedMemoryStream() : new MemoryStream())
                    using (MemoryStream decompressorOutput = new MemoryStream())
                    {
                        for (int i = 0; i < streamCount; i++)
                        {
                            using (var gz = new GZipStream(compressedStream, CompressionLevel.NoCompression, true))
                            {
                                for (int j = 0; j < bytesPerStream; j++)
                                {
                                    byte b = (byte)((i * j) % 256);
                                    gz.WriteByte(b);
                                    correctDecompressedOutput.WriteByte(b);
                                }
                            }
                        }
                        compressedStream.Seek(0, SeekOrigin.Begin);

                        var decompressor = CreateStream(compressedStream, CompressionMode.Decompress);

                        var  bytes = new byte[bufferSize];
                        bool finished = false;
                        int  retCount = 0, totalRead = 0;
                        while (!finished)
                        {
                            switch (scenario)
                            {
                            case TestScenario.ReadAsync:
                                try
                                {
                                    retCount = await decompressor.ReadAsync(bytes, 0, bufferSize);

                                    totalRead += retCount;
                                    if (retCount != 0)
                                    {
                                        await decompressorOutput.WriteAsync(bytes, 0, retCount);
                                    }
                                    else
                                    {
                                        finished = true;
                                    }
                                }
                                catch (Exception)
                                {
                                    throw new Exception(retCount + " " + totalRead);
                                }
                                break;

                            case TestScenario.ReadByte:
                                int b = decompressor.ReadByte();

                                if (b != -1)
                                {
                                    decompressorOutput.WriteByte((byte)b);
                                }
                                else
                                {
                                    finished = true;
                                }

                                break;

                            case TestScenario.Read:
                                retCount = decompressor.Read(bytes, 0, bufferSize);

                                if (retCount != 0)
                                {
                                    decompressorOutput.Write(bytes, 0, retCount);
                                }
                                else
                                {
                                    finished = true;
                                }

                                break;

                            case TestScenario.Copy:
                                decompressor.CopyTo(decompressorOutput, bufferSize);
                                finished = true;
                                break;

                            case TestScenario.CopyAsync:
                                await decompressor.CopyToAsync(decompressorOutput, bufferSize);

                                finished = true;
                                break;
                            }
                        }
                        decompressor.Dispose();
                        decompressorOutput.Position = 0;

                        byte[] decompressorOutputBytes = decompressorOutput.ToArray();
                        byte[] correctOutputBytes      = correctDecompressedOutput.ToArray();

                        Assert.Equal(correctOutputBytes.Length, decompressorOutputBytes.Length);
                        for (int i = 0; i < correctOutputBytes.Length; i++)
                        {
                            Assert.Equal(correctOutputBytes[i], decompressorOutputBytes[i]);
                        }
                    }
        }
        private void CompleteF2L()
        {
            List <Tuple <Cube, Cube> > unsolvedPairs = GetPairs(this.Rubik).ToList();

            while (unsolvedPairs.Count > 0) // 4 pairs
            {
                Tuple <Cube, Cube> currentPair = unsolvedPairs.First();

                Cube edge   = currentPair.Item1;
                Cube corner = currentPair.Item2;

                CubePosition target = new CubePosition(Rubik.GetTargetFlags(corner));

                if (!corner.Position.HasFlag(CubeFlag.TopLayer) && Rubik.GetTargetFlags(corner) != corner.Position.Flags)
                {
                    CubeFlag rotationLayer = CubeFlagService.FirstNotInvalidFlag(corner.Position.Flags, CubeFlag.BottomLayer);
                    bool     direction     = new TestScenario(Rubik, new LayerMove(rotationLayer)).TestCubePosition(corner, CubeFlag.TopLayer);
                    SolverMove(rotationLayer, direction);
                    SolverMove(CubeFlag.TopLayer, true);
                    SolverMove(rotationLayer, !direction);
                }
                // move edge to top position if necessary
                if (!edge.Position.HasFlag(CubeFlag.TopLayer) && Rubik.GetTargetFlags(edge) != edge.Position.Flags)
                {
                    CubeFlag rotationLayer = CubeFlagService.FirstNotInvalidFlag(edge.Position.Flags, CubeFlag.MiddleLayer);
                    bool     direction     = new TestScenario(Rubik, new LayerMove(rotationLayer)).TestCubePosition(edge, CubeFlag.TopLayer);
                    SolverMove(rotationLayer, direction);
                    while ((corner.Position.HasFlag(rotationLayer) && !corner.Position.HasFlag(CubeFlag.BottomLayer)) || edge.Position.HasFlag(rotationLayer))
                    {
                        SolverMove(CubeFlag.TopLayer, true);
                    }
                    SolverMove(rotationLayer, !direction);
                }

                // detect right and front slice
                CubeFlag rightSlice = CubeFlagService.ToInt(target.X) == CubeFlagService.ToInt(target.Z) ? target.Z : target.X;
                CubeFlag frontSlice = CubeFlagService.FirstNotInvalidFlag(target.Flags, CubeFlag.YFlags | rightSlice);

                while (!corner.Position.HasFlag(target.Flags & ~CubeFlag.BottomLayer))
                {
                    SolverMove(CubeFlag.TopLayer, true);
                }

                PatternFilter filter = new PatternFilter(new Func <Pattern, Pattern, bool>(delegate(Pattern p1, Pattern p2)
                {
                    PatternItem item = new PatternItem(corner.Position, Solvability.GetOrientation(this.Rubik, corner), target.Flags);
                    return(p2.Items.Any(i => i.Equals(item)));
                }), true);

                Algorithm algo = null;
                for (int i = 0; i < 4; i++)
                {
                    F2LPattern pattern = new F2LPattern(Rubik.GetTargetFlags(edge), Rubik.GetTargetFlags(corner), rightSlice, frontSlice);
                    algo = pattern.FindBestMatch(Pattern.FromRubik(Rubik), CubeFlag.None, filter);
                    if (algo != null)
                    {
                        SolverAlgorithm(algo); break;
                    }
                    SolverMove(CubeFlag.TopLayer, true);
                }

                int count = unsolvedPairs.Count;
                unsolvedPairs = GetPairs(this.Rubik).ToList();
                if (unsolvedPairs.Count == count)
                {
                    this.BroadcastOnSolutionError("Complete first two layers", "Wrong algorithm");
                    return;
                }
            }
        }
Esempio n. 24
0
 public Task <HttpStatusCode> SaveTestScenario(TestScenario testScenario)
 {
     return(_cosmosRepository.UpsertAsync(testScenario));
 }
Esempio n. 25
0
        static void Main(string[] args)
        {
            int    maxCases       = Int32.MaxValue;
            string rootPath       = Path.GetDirectoryName(typeof(Program).Assembly.Location);
            string scenarioSuffix = "";

            if (args.Length > 0)
            {
                rootPath = args[0];
            }
            if (args.Length > 2)
            {
                maxCases       = Int32.Parse(args[1]);
                scenarioSuffix = args[2];
            }
            using StreamWriter twOutputTest = new StreamWriter(Path.Combine(rootPath, @$ "{TestAssemblyName}{scenarioSuffix}.il"));

            StringWriter swMainMethodBody   = new StringWriter();
            StringWriter swTestClassMethods = new StringWriter();

            EmitTestGlobalHeader(twOutputTest);
            EmitAssemblyRecord(twOutputTest, TestAssemblyName);

            int currentCase = 0;

            foreach (var scenario in TestScenario.GetScenarios())
            {
                if ((++currentCase) > maxCases)
                {
                    break;
                }
                string scenarioName = scenario.ToString();

                // Emit interface
                ClassDesc iface = new ClassDesc();
                iface.ClassFlags    = "interface public abstract auto ansi";
                iface.GenericParams = scenario.InterfaceTypeGenericParams;
                iface.Name          = "Interface" + scenarioName + GenericTypeSuffix(scenario.InterfaceTypeGenericParams);;

                EmitClass(twOutputTest, iface);
                MethodDesc ifaceMethod = new MethodDesc();
                ifaceMethod.HasBody     = false;
                ifaceMethod.MethodFlags = "public newslot virtual abstract static";
                ifaceMethod.ReturnType  = scenario.InterfaceReturnType;
                ifaceMethod.Name        = "Method";

                EmitMethod(twOutputTest, ifaceMethod);
                EmitEndMethod(twOutputTest, ifaceMethod);
                EmitEndClass(twOutputTest, iface);

                // Emit base class which implements static method to implement interface. Mark it abstract if we don't put the methodimpl there
                ClassDesc baseType = new ClassDesc();
                baseType.BaseType = "[System.Runtime]System.Object";
                switch (scenario.InterfaceImplementationApproach)
                {
                case InterfaceImplementationApproach.OnBaseType:
                case InterfaceImplementationApproach.OnBothBaseAndDerived:
                    baseType.ClassFlags = "public auto ansi";
                    break;

                case InterfaceImplementationApproach.OnBothBaseAndDerivedBaseIsAbstract:
                    baseType.ClassFlags = "public abstract auto ansi";
                    break;

                default:
                    throw new Exception("Unknown interface approach");
                }
                baseType.GenericParams = scenario.BaseTypeGenericParams;
                baseType.Name          = "Base" + scenarioName + GenericTypeSuffix(scenario.BaseTypeGenericParams);
                if (scenario.InterfaceImplementationApproach.ToString().Contains("Base"))
                {
                    baseType.InterfacesImplemented = new string[] { ToILDasmTypeName(iface.Name, scenario.InterfaceTypeInstantiationOnBaseType) };
                }
                EmitClass(twOutputTest, baseType);
                switch (scenario.InterfaceImplementationApproach)
                {
                case InterfaceImplementationApproach.OnBaseType:
                case InterfaceImplementationApproach.OnBothBaseAndDerived:
                    MethodDesc ifaceImplMethod = new MethodDesc();
                    ifaceImplMethod.HasBody     = true;
                    ifaceImplMethod.MethodFlags = "public static";
                    ifaceImplMethod.ReturnType  = scenario.BaseTypeReturnType;
                    ifaceImplMethod.Name        = "Method";
                    EmitMethod(twOutputTest, ifaceImplMethod);
                    twOutputTest.WriteLine($"    .override method {scenario.InterfaceReturnType} {ToILDasmTypeName(iface.Name, scenario.InterfaceTypeInstantiationOnBaseType)}::Method()");
                    twOutputTest.WriteLine($"    .locals init ({scenario.BaseTypeReturnType} V_O)");
                    twOutputTest.WriteLine($"    ldloca.s 0");
                    twOutputTest.WriteLine($"    initobj {scenario.BaseTypeReturnType}");
                    twOutputTest.WriteLine($"    ldloc.0");
                    twOutputTest.WriteLine($"    ret");
                    EmitEndMethod(twOutputTest, ifaceImplMethod);
                    break;

                case InterfaceImplementationApproach.OnBothBaseAndDerivedBaseIsAbstract:
                    break;

                default:
                    throw new Exception("Unknown interface approach");
                }
                EmitEndClass(twOutputTest, baseType);

                // Emit derived class.
                ClassDesc derivedType = new ClassDesc();
                derivedType.BaseType = ToILDasmTypeName(baseType.Name, scenario.BaseTypeInstantiationOnDerivedType);
                switch (scenario.InterfaceImplementationApproach)
                {
                case InterfaceImplementationApproach.OnBaseType:
                case InterfaceImplementationApproach.OnBothBaseAndDerived:
                case InterfaceImplementationApproach.OnBothBaseAndDerivedBaseIsAbstract:
                    derivedType.ClassFlags = "public auto ansi";
                    break;

                default:
                    throw new Exception("Unknown interface approach");
                }
                derivedType.Name          = "Derived" + scenarioName + GenericTypeSuffix(scenario.DerivedTypeGenericParams);
                derivedType.GenericParams = scenario.DerivedTypeGenericParams;
                if (scenario.InterfaceImplementationApproach.ToString().Contains("Derived"))
                {
                    derivedType.InterfacesImplemented = new string[] { ToILDasmTypeName(iface.Name, scenario.InterfaceTypeInstantiationOnDerivedType) };
                }

                EmitClass(twOutputTest, derivedType);
                switch (scenario.InterfaceImplementationApproach)
                {
                case InterfaceImplementationApproach.OnBaseType:
                case InterfaceImplementationApproach.OnBothBaseAndDerived:
                    break;

                case InterfaceImplementationApproach.OnBothBaseAndDerivedBaseIsAbstract:
                    MethodDesc ifaceImplMethod = new MethodDesc();
                    ifaceImplMethod.HasBody     = true;
                    ifaceImplMethod.MethodFlags = "public static";
                    ifaceImplMethod.ReturnType  = scenario.DerivedTypeReturnType;
                    ifaceImplMethod.Name        = "MethodImplOnDerived";
                    EmitMethod(twOutputTest, ifaceImplMethod);
                    twOutputTest.WriteLine($"    .override method {scenario.InterfaceReturnType} {ToILDasmTypeName(iface.Name, scenario.InterfaceTypeInstantiationOnDerivedType)}::Method()");
                    twOutputTest.WriteLine($"    .locals init ({scenario.DerivedTypeReturnType} V_O)");
                    twOutputTest.WriteLine($"    ldloca.s 0");
                    twOutputTest.WriteLine($"    initobj {scenario.DerivedTypeReturnType}");
                    twOutputTest.WriteLine($"    ldloc.0");
                    twOutputTest.WriteLine($"    ret");
                    EmitEndMethod(twOutputTest, ifaceImplMethod);
                    break;

                default:
                    throw new Exception("Unknown interface approach");
                }
                EmitEndClass(twOutputTest, derivedType);

                // Emit test method which performs constrained call to hit the method
                MethodDesc mdIndividualTestMethod = new MethodDesc();
                string     basicTestMethodName    = $"Test_{scenarioName}";
                mdIndividualTestMethod.Name        = basicTestMethodName;
                mdIndividualTestMethod.HasBody     = true;
                mdIndividualTestMethod.MethodFlags = "public static";
                mdIndividualTestMethod.MethodImpls = null;
                mdIndividualTestMethod.ReturnType  = "void";
                mdIndividualTestMethod.Arguments   = "";

                EmitMethod(swTestClassMethods, mdIndividualTestMethod);
                swTestClassMethods.WriteLine($"    constrained. {ToILDasmTypeName(derivedType.Name, scenario.DerivedTypeInstantiation)}");
                swTestClassMethods.WriteLine($"    call {scenario.CallReturnType} {ToILDasmTypeName(iface.Name, scenario.CallInterfaceTypeInstantiation)}::Method()");
                if (scenario.CallReturnType != "void")
                {
                    // TODO: should we rather convert the value to string and stsfld Statics.String?
                    swTestClassMethods.WriteLine($"    pop");
                }
                swTestClassMethods.WriteLine($"    ldstr \"{scenarioName}\"");
                swTestClassMethods.WriteLine($"    ldnull");
                swTestClassMethods.WriteLine($"    call void {CommonCsPrefix}Statics::CheckForFailure(string,string)");
                swTestClassMethods.WriteLine($"    ret");
                EmitEndMethod(swTestClassMethods, mdIndividualTestMethod);
                // Call test method from main method
                swMainMethodBody.WriteLine("    .try {");
                swMainMethodBody.WriteLine($"        call void TestEntrypoint::{mdIndividualTestMethod.Name}()");
                swMainMethodBody.WriteLine($"        leave.s {scenarioName}Done");
                swMainMethodBody.WriteLine("    } catch [System.Runtime]System.Exception {");
                swMainMethodBody.WriteLine($"        stloc.0");
                swMainMethodBody.WriteLine($"        ldstr \"{scenarioName}\"");
                swMainMethodBody.WriteLine($"        ldnull");
                swMainMethodBody.WriteLine($"        ldloc.0");
                swMainMethodBody.WriteLine($"        callvirt   instance string [System.Runtime]System.Object::ToString()");
                swMainMethodBody.WriteLine($"        call void [TypeHierarchyCommonCs]Statics::CheckForFailure(string,string,string)");
                swMainMethodBody.WriteLine($"        leave.s {scenarioName}Done");
                swMainMethodBody.WriteLine("    }");
                swMainMethodBody.WriteLine($"{scenarioName}Done: nop");

                string GenericTypeSuffix(string genericParams)
                {
                    if (String.IsNullOrEmpty(genericParams))
                    {
                        return("");
                    }

                    return($"`{genericParams.Split(',').Length}");
                }
            }

            ClassDesc mainClass = new ClassDesc();

            mainClass.BaseType   = "[System.Runtime]System.Object";
            mainClass.ClassFlags = "public auto ansi";
            mainClass.Name       = "TestEntrypoint";

            EmitClass(twOutputTest, mainClass);

            twOutputTest.Write(swTestClassMethods.ToString());

            MethodDesc mainMethod = new MethodDesc();

            mainMethod.Name        = "Main";
            mainMethod.Arguments   = "";
            mainMethod.ReturnType  = "int32";
            mainMethod.MethodImpls = null;
            mainMethod.HasBody     = true;
            mainMethod.MethodFlags = "public static";

            EmitMethod(twOutputTest, mainMethod);
            twOutputTest.WriteLine("    .entrypoint");
            twOutputTest.WriteLine("    .locals init (class [System.Runtime]System.Exception V_0)");
            twOutputTest.Write(swMainMethodBody.ToString());
            twOutputTest.WriteLine($"    call int32 { CommonCsPrefix}Statics::ReportResults()");
            twOutputTest.WriteLine("    ret");

            EmitEndMethod(twOutputTest, mainMethod);
            EmitEndClass(twOutputTest, mainClass);
        }
 public void OpenSalesOrderList()
 {
     // Open Page "Sales Order List" which contains a list of all sales orders
     TestScenario.Run(OrderProcessorUserContextManager, TestContext,
                      userContext => TestScenario.RunPageAction(TestContext, userContext, SalesOrderListPageId));
 }
Esempio n. 27
0
        public void WhenEventsInThreeConsecutiveIntervals()
        {
            this.tableName = "WhenEventsInThreeConsecutiveIntervals";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

            AzureTableHelper.DeleteTable(connectionString, this.tableName);
            var logger = TestEventSource.Logger;

            var bufferingInterval = TimeSpan.FromSeconds(6);
            var insertionInterval = TimeSpan.FromSeconds(2);

            TestScenario.With1Listener(
                logger,
                (listener, errorsListener) =>
            {
                listener.LogToWindowsAzureTable("mytestinstance", connectionString, this.tableName, bufferingInterval: bufferingInterval);
                listener.EnableEvents(logger, EventLevel.Informational);

                // 1st interval: Log 10 events
                for (int i = 0; i < 10; i++)
                {
                    logger.Informational("Message1");
                }

                // 1st interval: Wait for the buffer to flush at end of interval
                Task.Delay(bufferingInterval).Wait();
                // 2nd interval: start

                // 1st interval: Wait for the events to be written and assert
                Task.Delay(insertionInterval).Wait();
                Assert.AreEqual(10, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                // 2nd interval: Log 10 events
                for (int i = 0; i < 10; i++)
                {
                    logger.Informational("Message1");
                }

                // 2nd interval: Wait for the buffer to flush at end of interval
                Task.Delay(bufferingInterval).Wait();
                // 3rd interval: start

                // 2nd interval: Wait for the events to be written and assert
                Task.Delay(insertionInterval).Wait();
                Assert.AreEqual(20, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                // 3rd interval: Log 10 events
                for (int i = 0; i < 10; i++)
                {
                    logger.Informational("Message1");
                }

                // 3rd interval: Wait for the buffer to flush at end of interval
                Task.Delay(bufferingInterval).Wait();
                // 4th interval: start

                // 3rd interval: Wait for the events to be written and assert
                Task.Delay(insertionInterval).Wait();
                Assert.AreEqual(30, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                // No errors should have been reported
                Assert.AreEqual(string.Empty, errorsListener.ToString());
            });

            // No more events should have been written during the last flush in the Dispose
            Assert.AreEqual(30, AzureTableHelper.GetEventsCount(connectionString, this.tableName));
        }
 public void CreateAndPostSalesOrder()
 {
     TestScenario.Run(OrderProcessorUserContextManager, TestContext, RunCreateAndPostSalesOrder);
 }
Esempio n. 29
0
        public List <TestCase> GetTestCases()
        {
            //Excel.Application xlApp = new Excel.Application();
            //Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(_fileLocation);
            //Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            //Excel.Range xlRange = xlWorksheet.UsedRange;

            Console.WriteLine("Test Cases are currently being read.");

            int rowCount = _xlRange.Rows.Count;
            int colCount = _xlRange.Columns.Count;

            int headerRow = 7;

            List <int[]> rowNumbers = new List <int[]>();

            // Find subset of rows for each test case as a array of [Start, End] values
            int start = headerRow;

            for (int i = headerRow + 1; i <= rowCount; i++)
            {
                if (_xlRange.Cells[i, 4] != null && _xlRange.Cells[i, 4].Value2 != null)
                {
                    int[] currTestCase = { start, i - 1 };
                    rowNumbers.Add(currTestCase);
                    start = i;
                }
            }
            int[] lastTestCase = { start, rowCount };
            rowNumbers.Add(lastTestCase);

            //foreach (var currRows in rowNumbers)
            //{
            //    Console.WriteLine(currRows[0] + " " + currRows[1]);
            //}

            List <TestCase> res = new List <TestCase>();

            // First row is a list header row. Do not need for implementation.
            // This is assuming that the test case upload style is standardized

            // Iterate through each subset of rows for each test case
            using (var progress = new ProgressBar())
            {
                double totalCount = rowNumbers.Count;
                double currCount  = 1;

                foreach (var currRow in rowNumbers)
                {
                    currCount += 1;
                    progress.Report(currCount / totalCount);

                    int startRow = currRow[0];
                    int endRow   = currRow[1];

                    //int testVal = (int)char.GetNumericValue(xlRange.Cells[startRow, 6].Value2[0]);
                    //System.Diagnostics.Debug.WriteLine(testVal);

                    TestCase currTestCase = new TestCase();

                    if (_xlRange.Cells[startRow, 1].Value2 != null)
                    {
                        currTestCase.TestCaseId = Convert.ToInt32(_xlRange.Cells[startRow, 1].Value2);
                    }

                    if (_xlRange.Cells[startRow, 2].Value2 != null)
                    {
                        currTestCase.TestScenarios = new List <TestScenario>();

                        string   testScenarioIds     = _xlRange.Cells[startRow, 2].Value2.ToString();
                        string[] testScenarioIdArray = testScenarioIds.Split(',').Select(x => x.Trim())
                                                       .Where(x => !string.IsNullOrWhiteSpace(x))
                                                       .ToArray();
                        foreach (string testScenarioId in testScenarioIdArray)
                        {
                            TestScenario currTestScenario = new TestScenario
                            {
                                TestScenarioId = Convert.ToInt32(testScenarioId)
                            };
                            currTestCase.TestScenarios.Add(currTestScenario);
                        }
                    }

                    currTestCase.TestCaseName       = _xlRange.Cells[startRow, 4].Value2;
                    currTestCase.TestObjective      = _xlRange.Cells[startRow, 5].Value2;
                    currTestCase.TestDescription    = _xlRange.Cells[startRow, 6].Value2;
                    currTestCase.PreCondition       = _xlRange.Cells[startRow, 7].Value2;
                    currTestCase.Priority           = (int)char.GetNumericValue(_xlRange.Cells[startRow, 8].Value2[0]);
                    currTestCase.PriorityString     = _xlRange.Cells[startRow, 8].Value2;
                    currTestCase.Complexity         = _xlRange.Cells[startRow, 9].Value2;
                    currTestCase.ScenarioType       = _xlRange.Cells[startRow, 10].Value2;
                    currTestCase.Application        = _xlRange.Cells[startRow, 11].Value2;
                    currTestCase.ApplicationArea    = _xlRange.Cells[startRow, 12].Value2;
                    currTestCase.ApplicationProcess = _xlRange.Cells[startRow, 13].Value2;
                    currTestCase.ApplicationSubArea = _xlRange.Cells[startRow, 14].Value2;
                    currTestCase.TestCaseType       = _xlRange.Cells[startRow, 15].Value2;

                    currTestCase.UserName = _userName;

                    for (int i = startRow; i <= endRow; i++)
                    {
                        if (_xlRange.Cells[i, 16].Value2 != null && _xlRange.Cells[i, 17].Value2 != null && _xlRange.Cells[i, 18] != null)
                        {
                            currTestCase.AddStep(i - startRow + 1, _xlRange.Cells[i, 17].Value2, _xlRange.Cells[i, 18].Value2);
                        }
                        //currTestCase.AddStep(_xlRange.Cells[i, 16].Value2, _xlRange.Cells[i, 17].Value2);
                        //if (startRow == 325)
                        //{
                        //    Console.WriteLine(xlRange.Cells[i, 16].Value2 + " " + xlRange.Cells[i, 17].Value2);
                        //}
                    }

                    res.Add(currTestCase);
                }
            }

            Console.WriteLine(res.Count + " Test Cases have been read");

            return(res);
        }
Esempio n. 30
0
 public void VerifyScenario(TestScenario scenario) => scenario.Execute(DotNetHelper);
Esempio n. 31
0
        public void WhenUsingCustomSinkBuiltInSinksForSameSource()
        {
            string fileName1 = "multipleFlatFile.log";

            File.Delete(fileName1);
            string fileName2 = "multipleMockFlatFile.log";

            File.Delete(fileName2);
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);

            string message  = string.Concat("Message ", Guid.NewGuid());
            string message2 = string.Concat("Message2 ", Guid.NewGuid());
            IEnumerable <string> entries  = null;
            IEnumerable <string> entries2 = null;
            var svcConfiguration          = TraceEventServiceConfiguration.Load("Configurations\\CustomSink\\Multiple.xml");

            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
            {
                var logger = MockEventSourceOutProc.Logger;
                logger.LogSomeMessage(message);
                logger.LogSomeMessage(message2);

                entries  = FlatFileHelper.PollUntilTextEventsAreWritten(fileName1, 10, "--==--");
                entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName2, 10, "==-==");
                DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 4);
            });

            Assert.IsTrue(File.Exists(fileName1));
            Assert.AreEqual <int>(2, entries.Count());
            StringAssert.Contains(entries.First().ToString(), message);
            StringAssert.Contains(entries.Last().ToString(), message2);

            Assert.IsTrue(File.Exists(fileName2));
            Assert.AreEqual <int>(2, entries2.Count());
            StringAssert.Contains(entries2.First().ToString(), message);
            StringAssert.Contains(entries2.Last().ToString(), message2);

            var dt = DatabaseHelper.GetLoggedTable(validConnectionString);

            Assert.AreEqual(4, dt.Rows.Count);

            var rowsWithMessage1 = dt.Select(string.Format("Payload like '%{0}%'", message));

            Assert.AreEqual(2, rowsWithMessage1.Count());
            var dr = rowsWithMessage1[0];

            Assert.AreEqual(4, (int)dr["Level"]);
            Assert.AreEqual(8, (int)dr["EventID"]);
            Assert.AreEqual("testingInstance", dr["InstanceName"].ToString());
            StringAssert.Contains((string)dr["Payload"], message);
            dr = rowsWithMessage1[1];
            Assert.AreEqual(4, (int)dr["Level"]);
            Assert.AreEqual(8, (int)dr["EventID"]);
            Assert.AreEqual("testingInstance", dr["InstanceName"].ToString());
            StringAssert.Contains((string)dr["Payload"], message);

            var rowsWithMessage2 = dt.Select(string.Format("Payload like '%{0}%'", message2));

            Assert.AreEqual(2, rowsWithMessage2.Count());
            dr = rowsWithMessage2[0];
            Assert.AreEqual(4, (int)dr["Level"]);
            Assert.AreEqual(8, (int)dr["EventID"]);
            Assert.AreEqual("testingInstance", dr["InstanceName"].ToString());
            StringAssert.Contains((string)dr["Payload"], message2);
            dr = rowsWithMessage2[1];
            Assert.AreEqual(4, (int)dr["Level"]);
            Assert.AreEqual(8, (int)dr["EventID"]);
            Assert.AreEqual("testingInstance", dr["InstanceName"].ToString());
            StringAssert.Contains((string)dr["Payload"], message2);
        }