Exemplo n.º 1
0
        private static async Task ExecScenarioAll(IScenario scenario, string msSqlConnectionString, string pgSqlConnectionString, string mySqlConnectionString)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine();
            Console.WriteLine("-MS SQL Test-------");
            stopwatch.Restart();
            await ExecMsSql(scenario, msSqlConnectionString);

            stopwatch.Stop();
            Console.WriteLine($"-MS SQL Test End: {stopwatch.ElapsedMilliseconds} ms");

            Console.WriteLine("-Postgres Test-----");
            stopwatch.Start();
            await ExecNpgSql(scenario, pgSqlConnectionString);

            stopwatch.Stop();
            Console.WriteLine($"-Postgres Test End: {stopwatch.ElapsedMilliseconds} ms");

            Console.WriteLine();
            Console.WriteLine("-MY SQL Test-------");
            stopwatch.Restart();
            await ExecMySql(scenario, mySqlConnectionString);

            stopwatch.Stop();
            Console.WriteLine($"-MY SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
        }
Exemplo n.º 2
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dataSession">Active data session</param>
        /// <param name="entitiesExpression">Entities expression</param>
        protected MockRepositoryBase(IDataSession dataSession, Func <TScenarioInterface, IList <TEntity> > entitiesExpression)
        {
            //Arguments validation
            if (dataSession == null)
            {
                throw new ArgumentNullException(nameof(dataSession));
            }

            //Convert to IMockDataSession
            var mockupSession = dataSession.AsMockDataSession();

            //Get scenario from data session
            IScenario scenarioFromDataSession = mockupSession.GetScenario();

            //Try cast of scenario to provided interface
            if (!(scenarioFromDataSession is TScenarioInterface castedScenario))
            {
                throw new InvalidCastException("Scenario contained on data session is of " +
                                               $"type '{scenarioFromDataSession.GetType().FullName}' and cannot be converted " +
                                               $"to type '{typeof(TScenarioInterface).FullName}'.");
            }

            //Set data session and scenario
            DataSession = mockupSession;
            Scenario    = castedScenario;

            //Initialize working mocked entities
            MockedEntities = entitiesExpression(Scenario);
        }
Exemplo n.º 3
0
        public ScenarioRunner(
            IScenario scenario,
            IMessageBus messageBus,
            Type scenarioClass,
            object[] constructorArguments,
            MethodInfo scenarioMethod,
            object[] scenarioMethodArguments,
            string skipReason,
            IReadOnlyList <BeforeAfterTestAttribute> beforeAfterScenarioAttributes,
            ExceptionAggregator aggregator,
            CancellationTokenSource cancellationTokenSource)
        {
            Guard.AgainstNullArgument(nameof(scenario), scenario);
            Guard.AgainstNullArgument(nameof(messageBus), messageBus);
            Guard.AgainstNullArgument(nameof(aggregator), aggregator);

            this.scenario                      = scenario;
            this.messageBus                    = messageBus;
            this.scenarioClass                 = scenarioClass;
            this.constructorArguments          = constructorArguments;
            this.scenarioMethod                = scenarioMethod;
            this.scenarioMethodArguments       = scenarioMethodArguments;
            this.skipReason                    = skipReason;
            this.beforeAfterScenarioAttributes = beforeAfterScenarioAttributes;
            this.parentAggregator              = aggregator;
            this.cancellationTokenSource       = cancellationTokenSource;
        }
Exemplo n.º 4
0
        private IStorEvilJob GetJob(RemoteTask remoteTask, IScenario scenario)
        {
            InPlaceStoryRunner handler = BuildInPlaceRunner(remoteTask);
            IStoryProvider provider = new SingleScenarioStoryProvider(scenario);

            return new StorEvilJob(provider, handler);
        }
Exemplo n.º 5
0
        public StepTest(IScenario scenario, string displayName)
        {
            Guard.AgainstNullArgument(nameof(scenario), scenario);

            this.Scenario    = scenario;
            this.DisplayName = displayName;
        }
#pragma warning disable IDE0060 // Remove unused parameter 'text' if it is not part of a shipped public API
        public void UsingMetadata(string text, IStepContext stepContext, IStep step, IScenario scenario)
#pragma warning restore IDE0060 // Remove unused parameter 'text' if it is not part of a shipped public API
        {
            "When I execute a step".x(context => stepContext = context)
            .Teardown(context => context.AssertSame(stepContext));

            "Then the step context contains metadata about the step".x(() =>
            {
                step = stepContext.Step.AssertNotNull();
                var stepDisplayName = step.DisplayName;
                stepDisplayName.AssertEqual($"Xwellbehaved.MetadataFeature.UsingMetadata(text: \"abc\") [01] ({StepType.Scenario}): When I execute a step");
            });

            "And the step contains metadata about the scenario".x(() =>
            {
                scenario = step.Scenario.AssertNotNull();
                var scenarioDisplayName = scenario.DisplayName;
                scenarioDisplayName.AssertEqual("Xwellbehaved.MetadataFeature.UsingMetadata(text: \"abc\")");
            });

            "And the step contains metadata about the scenario outline".x(() =>
            {
                var scenarioScenarioOutline = scenario.ScenarioOutline;
                scenarioScenarioOutline.AssertNotNull();
                scenarioScenarioOutline.DisplayName.AssertEqual("Xwellbehaved.MetadataFeature.UsingMetadata");
            });
        }
Exemplo n.º 7
0
        public ScenarioRunner(
            IScenario scenario
            , IMessageBus messageBus
            , Type scenarioClass
            , object[] constructorArguments
            , MethodInfo scenarioMethod
            , object[] scenarioMethodArguments
            , string skipReason
            , IReadOnlyList <BeforeAfterTestAttribute> beforeAfterScenarioAttributes
            , ExceptionAggregator aggregator
            , CancellationTokenSource cancellationTokenSource)
        {
            //Guard.AgainstNullArgument(nameof(scenario), scenario);
            //Guard.AgainstNullArgument(nameof(messageBus), messageBus);
            //Guard.AgainstNullArgument(nameof(aggregator), aggregator);

#if DEBUG
            scenario.RequiresNotNull(nameof(scenario));
            messageBus.RequiresNotNull(nameof(messageBus));
            aggregator.RequiresNotNull(nameof(aggregator));
#endif

            this._scenario   = scenario;
            this._messageBus = messageBus;
            // TODO: TBD: #3 MWP 2020-07-01 03:14:04 PM / should there be guards on these?
            this._scenarioClass           = scenarioClass;
            this._constructorArguments    = constructorArguments;
            this._scenarioMethod          = scenarioMethod;
            this._scenarioMethodArguments = scenarioMethodArguments;
            this._skipReason = skipReason;
            this._beforeAfterScenarioAttributes = beforeAfterScenarioAttributes;
            this._parentAggregator        = aggregator;
            this._cancellationTokenSource = cancellationTokenSource;
        }
 private StoryMetadata CreateSpecificationMetadata(IScenario specification)
 {
     var title = specification.GetType().GetProperty("SUT").PropertyType.Name;
     var story = (Story)Activator.CreateInstance(specification.Story);
     var storyAttribute = new StoryAttribute() { Title = title, TitlePrefix = story.TitlePrefix };
     return new StoryMetadata(specification.Story, storyAttribute);
 }
Exemplo n.º 9
0
        private IStorEvilJob GetJob(RemoteTask remoteTask, IScenario scenario)
        {
            _listener.SetCurrentTask(remoteTask);
            IStoryProvider provider = new SingleScenarioStoryProvider(scenario);

            return(new StorEvilJob(provider, _runner));
        }
 public StorEvilScenarioElement(StorEvilTestProvider provider, UnitTestElement parent, IProject project,
                                string title, Scenario scenario)
     : base(provider, parent, project, title)
 {
     _namespace = new UnitTestNamespace(project.Name);
     Scenario = scenario;
 }
Exemplo n.º 11
0
        public ScenarioInvoker(
            IScenario scenario,
            IMessageBus messageBus,
            Type scenarioClass,
            object[] constructorArguments,
            MethodInfo scenarioMethod,
            object[] scenarioMethodArguments,
            IReadOnlyList <BeforeAfterTestAttribute> beforeAfterScenarioAttributes,
            ExceptionAggregator aggregator,
            CancellationTokenSource cancellationTokenSource)
        {
            Guard.AgainstNullArgument("scenario", scenario);
            Guard.AgainstNullArgument("messageBus", messageBus);
            Guard.AgainstNullArgument("scenarioClass", scenarioClass);
            Guard.AgainstNullArgument("scenarioMethod", scenarioMethod);
            Guard.AgainstNullArgument("beforeAfterScenarioAttributes", beforeAfterScenarioAttributes);
            Guard.AgainstNullArgument("aggregator", aggregator);
            Guard.AgainstNullArgument("cancellationTokenSource", cancellationTokenSource);

            this.scenario                      = scenario;
            this.messageBus                    = messageBus;
            this.scenarioClass                 = scenarioClass;
            this.constructorArguments          = constructorArguments;
            this.scenarioMethod                = scenarioMethod;
            this.scenarioMethodArguments       = scenarioMethodArguments;
            this.beforeAfterScenarioAttributes = beforeAfterScenarioAttributes;
            this.aggregator                    = aggregator;
            this.cancellationTokenSource       = cancellationTokenSource;
        }
        protected override void AfterTestStarting()
        {
            base.AfterTestStarting();

            if (Aggregator.HasExceptions || SkipReason != null)
            {
                return;
            }

            try
            {
                var scenarioDiscoverer = ScenarioDiscovererFactory.GetDiscoverer(DiagnosticMessageSink, ScenarioTest.ScenarioIdentifier);
                Scenario = scenarioDiscoverer.GetScenario(ScenarioTest.ScenarioIdentifier);

                if (Scenario == null)
                {
                    throw new InvalidOperationException("Scenario is null (ScenarioDiscoverer returned no scenario).");
                }

                if (Scenario is IExecutableScenario executableScenario)
                {
                    Aggregator
                    .RunAsync(() => executableScenario.ExecuteAsync())
                    .Wait();
                }
            }
            catch (Exception e)
            {
                Aggregator.Add(e);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Get scenario of specified type from data session
        /// </summary>
        /// <typeparam name="TScenario">Type of scenario</typeparam>
        /// <param name="instance">Instance</param>
        /// <returns>Returns scenario</returns>
        public static TScenario GetScenario <TScenario>(this IDataSession instance)
        {
            //Arguments validation
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            //Try to cast to IMockDataSession
            IMockDataSession mockupSession = instance.AsMockDataSession();

            //Get scenario from data session
            IScenario scenarioFromDataSession = mockupSession.GetScenario();

            //Try cast of scenario to provided type
            if (!(scenarioFromDataSession is TScenario castedScenario))
            {
                throw new InvalidCastException("Scenario contained on data session is of " +
                                               $"type '{scenarioFromDataSession.GetType().FullName}' and cannot be converted " +
                                               $"to type '{typeof(TScenario).FullName}'.");
            }

            //Return scenario
            return(castedScenario);
        }
Exemplo n.º 14
0
        public void CustomGitRepositoryHandlerBasic(IScenario scenario)
        {
            var headers           = new System.Collections.Specialized.NameValueCollection();
            var request           = new Mock <HttpRequestBase>();
            var response          = new Mock <HttpResponseBase>();
            var context           = new Mock <HttpContextBase>();
            var environment       = new Mock <IEnvironment>();
            var repositoryFactory = new Mock <IRepositoryFactory>();
            var repository        = new Mock <IRepository>();

            repository.SetupGet(c => c.RepositoryType).Returns(RepositoryType.Git);
            repositoryFactory.Setup(c => c.GetCustomRepository())
            .Returns(scenario.RepositoryExists ? repository.Object : null);
            environment.SetupGet(c => c.RootPath).Returns(scenario.SiteRoot);
            environment.SetupProperty(c => c.RepositoryPath);
            request.SetupGet(c => c.Url).Returns(scenario.RequestUri);
            request.SetupGet(c => c.Headers).Returns(headers);
            response.SetupGet(c => c.OutputStream).Returns(new System.IO.MemoryStream());
            response.SetupProperty(c => c.StatusCode);
            context.SetupGet(c => c.Response).Returns(response.Object);
            context.SetupGet(c => c.Request).Returns(request.Object);

            CustomGitRepositoryHandler handler =
                CreateHandler(environment: environment.Object,
                              repositoryFactory: repositoryFactory.Object);

            handler.ProcessRequestBase(context.Object);
            scenario.Verify(environment.Object, (HttpStatusCode)response.Object.StatusCode);
        }
Exemplo n.º 15
0
        public SubProblemBuilder AddSubProblem(string key, IScenario problemModel)
        {
            var problemBuilder = problemModel.Apply(key, new SubProblemBuilder());

            SubProblems.Add(problemBuilder);
            return(problemBuilder);
        }
Exemplo n.º 16
0
        public async Task InPlaceDeploymentBasicTests(IScenario scenario)
        {
            var appName = KuduUtils.GetRandomWebsiteName(scenario.Name);
            await ApplicationManager.RunAsync(appName, async appManager =>
            {
                await appManager.SettingsManager.SetValue(SettingsKeys.RepositoryPath, "wwwroot");

                using (TestRepository testRepository = Git.Clone(scenario.Name, scenario.CloneUrl))
                {
                    var result = appManager.GitDeploy(testRepository.PhysicalPath);

                    // Inplace should not do KuduSync
                    Assert.DoesNotContain("KuduSync", result.GitTrace);

                    // Repository path should not exist
                    Assert.False(appManager.VfsManager.Exists(@"site\repository\.git"), @"Should not have site\repository\.git folder");

                    // Validate builder
                    Assert.Contains(scenario.BuilderTrace, result.GitTrace);
                }

                // Validate deployment status
                var results = (await appManager.DeploymentManager.GetResultsAsync()).ToList();
                Assert.Equal(1, results.Count);
                Assert.Equal(DeployStatus.Success, results[0].Status);

                // Validate site
                scenario.Verify(appManager);
            });
        }
Exemplo n.º 17
0
        public bool Include(Story story, IScenario scenario)
        {
            if (_tags.Count() == 0)
                return true;

            return AnyTagMatches(story.Tags) || AnyTagMatches(scenario.Tags);
        }
Exemplo n.º 18
0
        public Step(IScenario scenario, string displayName)
        {
            Guard.AgainstNullArgument("scenario", scenario);

            this.scenario    = scenario;
            this.displayName = displayName;
        }
 public override IOptimizationTestFactory CreateTestFactory(
     IScenario scenario, uint numSimulations, uint numSamples)
 {
     return
         (new SocialGPOptimizationTestFactory(
              (ISocialFitnessScenario)scenario.Clone(numSimulations, numSamples)));
 }
Exemplo n.º 20
0
        public async Task FetchHandlerBasicTests(IScenario scenario)
        {
            // Arrange
            var siteRoot           = @"x:\vdir0\site";
            var deploymentManager  = new MockDeploymentManager();
            var fileSystem         = GetFileSystem(siteRoot, scenario.WriteTimeUTCs.ToArray());
            var environment        = GetEnvironment(siteRoot);
            var serviceHookHandler = GetServiceHookHandler();
            var repositoryFactory  = GetRepositoryFactory();
            var handler            = CreateFetchHandler(deploymentManager: deploymentManager,
                                                        fileSystem: fileSystem.Object,
                                                        serviceHookHandler: serviceHookHandler.Object,
                                                        repositoryFactory: repositoryFactory.Object,
                                                        environment: environment.Object);

            // Test
            await handler.PerformDeployment(new DeploymentInfo
            {
                IsReusable      = scenario.IsReusable,
                Handler         = serviceHookHandler.Object,
                TargetChangeset = GetChangeSet()
            });

            // Assert
            Assert.Equal(scenario.DeployCount, deploymentManager.DeployCount);
        }
Exemplo n.º 21
0
        private void ReportScenarioFields(Tab tab, Model model, IProgressMessage progress, IProgressIndicator hmProgress)
        {
            IScenario scenario = (IScenario)model.DomainDataSet.ScenarioManager.Elements()[0];

            ReportSupportedFields(
                "Working with the scenario...",
                scenario.SupportedFields(),
                tab,
                hmProgress,
                progress,
                scenario.Id
                );


            //FieldCollection fields = scenario.SupportedFields();
            //FieldTypeReporter reporter;

            //string message = "Working with the scenario...";
            //hmProgress.AddTask(message).Steps = fields.Count;
            //hmProgress.IncrementTask();
            //hmProgress.BeginTask(fields.Count);

            //foreach (IField field in fields)
            //{
            //    hmProgress.IncrementStep();
            //    reporter = new FieldTypeReporter(field);
            //    tab.Chidren.Add(reporter.ToJson());
            //    progress.Message = reporter.ToString();
            //    ReportCollectionFieldsType(tab, progress, field, scenario.Id);
            //}

            hmProgress.EndTask();
        }
Exemplo n.º 22
0
        private static Story CreateBDDfyStory(IScenario scenario)
        {
            var story    = scenario.BDDfy();
            var metadata = new SpecifyStoryMetadataScanner().Scan(scenario);

            return(new Story(metadata, story.Scenarios.ToArray()));
        }
Exemplo n.º 23
0
 public void Construct()
 {
     Relay    = builder.CreateRele();
     Post     = builder.CreatePost();
     Handler  = builder.CreateHandler();
     Scenario = builder.CreateScenario();
 }
Exemplo n.º 24
0
        public Step(IScenario scenario, string displayName)
        {
            Guard.AgainstNullArgument("scenario", scenario);

            this.scenario = scenario;
            this.displayName = displayName;
        }
Exemplo n.º 25
0
        public IScenarioHandler Create(IIterationControl iterationContext)
        {
            IScenario        scenarioInstance = _factory.Create(iterationContext.ThreadId);
            IScenarioHandler scenarioHandler  = new ScenarioHandler(_globalCounters, new NotThreadSafeIdGenerator(), scenarioInstance, iterationContext);

            return(scenarioHandler);
        }
Exemplo n.º 26
0
        public override void Scenarios()
        {
            didCallScenarios = true;
            IScenario scenario = PrepareScenario();

            AddScenario(scenario);
        }
Exemplo n.º 27
0
 public PlaceController(IScenario scenario)
 {
     if (scenario != null)
     {
         _scenario = scenario;
     }
 }
Exemplo n.º 28
0
 public ScenarioHandler(IGlobalCountersControl globalCounters, IUniqueIdGenerator <int> threadIterationIdGenerator, IScenario scenario, IIterationControl context)
 {
     _scenario                   = scenario ?? throw new ArgumentNullException(nameof(scenario));
     _context                    = context ?? throw new ArgumentNullException(nameof(context));
     _globalCounters             = globalCounters ?? throw new ArgumentNullException(nameof(globalCounters));
     _threadIterationIdGenerator = threadIterationIdGenerator ?? throw new ArgumentNullException(nameof(threadIterationIdGenerator));
 }
 public Application(IRelay r, IHandler h, IPost p, IScenario s)
 {
     _relay    = r;
     _handler  = h;
     _post     = p;
     _scenario = s;
 }
Exemplo n.º 30
0
        public void LoadScenario(IScenario scenario)
        {
            var covidScenario = scenario as CovidScenario;

            Scenario = scenario;
            LoadSetupFiles(covidScenario);
        }
Exemplo n.º 31
0
        private async Task <BaseScenarioResult> RunScenario(IScenario scenario, ScenarioContext context)
        {
            BaseScenarioResult result;

            try
            {
                result = await Task.Run(() => this._scenarioExecutor.ExecuteScenario(scenario, context));

                result.Success = !result.Errors.Any();
            }
            catch (Exception exc)
            {
                result = new BaseScenarioResult();
                result.Errors.Add(new ScenarioError
                {
                    ErrorMessage = $"Unable to execute scenario. Error code: {LoggingEvents.ScenarioException}",
                    ErrorSource  = $"{this.GetType().Name}::{MethodBase.GetCurrentMethod().Name}",
                    ErrorType    = "Critical"
                });

                this._logger.LogError(LoggingEvents.ScenarioException, exc, exc.Message);
            }

            return(result);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Initialize the current scene
        /// set Device present parametrs
        /// loading texture and set the element start position
        /// </summary>
        private void InitializeScene()
        {
            try
            {
                //! Create scenarios.
                ballonAndBirdScenario = new BallonAndBirdScenario();
                appleAndBirdScenario  = new AppleAndBirdScenario();
                curScenario           = appleAndBirdScenario;
                //! Initialize the scenarios.
                appleAndBirdScenario.Initialize(device, Width, Height);
                ballonAndBirdScenario.Initialize(device, Width, Height);
                //! Add bird flutter step texture to the TextureList.
                ballonAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B10));
                ballonAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B11));
                ballonAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B12));
                ballonAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B13));
                ballonAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B14));

                appleAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B10));
                appleAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B11));
                appleAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B12));
                appleAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B13));
                appleAndBirdScenario.TextureList.Add(GraphicEngine.GraphicEngine.CreateTexture(device, Properties.Resources.B14));
            }
            catch (Exception ex)
            {
                xPFT.Exceptions.ExceptionHandler.LogError(ex);
            }
        }
Exemplo n.º 33
0
        public virtual IOptimizationTestFactory CreateTestFactory(IScenario scenario)
        {
            var numSimulations = scenario.TestsConfig.NumSimulations;
            var numSamples     = scenario.TestsConfig.NumSamples;

            return(this.CreateTestFactory(scenario, numSimulations, numSamples));
        }
Exemplo n.º 34
0
        public ScenarioRunner(
            IScenario scenario,
            IMessageBus messageBus,
            Type scenarioClass,
            object[] constructorArguments,
            MethodInfo scenarioMethod,
            object[] scenarioMethodArguments,
            string skipReason,
            IReadOnlyList<BeforeAfterTestAttribute> beforeAfterScenarioAttributes,
            ExceptionAggregator aggregator,
            CancellationTokenSource cancellationTokenSource)
        {
            Guard.AgainstNullArgument("scenario", scenario);
            Guard.AgainstNullArgument("messageBus", messageBus);
            Guard.AgainstNullArgument("aggregator", aggregator);

            this.scenario = scenario;
            this.messageBus = messageBus;
            this.scenarioClass = scenarioClass;
            this.constructorArguments = constructorArguments;
            this.scenarioMethod = scenarioMethod;
            this.scenarioMethodArguments = scenarioMethodArguments;
            this.skipReason = skipReason;
            this.beforeAfterScenarioAttributes = beforeAfterScenarioAttributes;
            this.parentAggregator = aggregator;
            this.cancellationTokenSource = cancellationTokenSource;
        }
Exemplo n.º 35
0
        private static void AssertCapturedItems(IScenario scenario, AppRunnerResult results)
        {
            foreach (var expectedOutput in scenario.Then.Captured)
            {
                var expectedType = expectedOutput.GetType();
                var actualOutput = results.TestCaptures.Get(expectedType);
                if (actualOutput == null)
                {
                    throw new AssertFailedException($"{expectedType.Name} should have been captured in the test run but wasn't");
                }
                actualOutput.ShouldBeEquivalentTo(expectedOutput, $"Captured {expectedType.Name}");
            }

            var actualOutputs = results.TestCaptures.Captured;

            if (!scenario.Then.AllowUnspecifiedCaptures && actualOutputs.Count > scenario.Then.Captured.Count)
            {
                var expectedOutputTypes = new HashSet <Type>(scenario.Then.Captured.Select(o => o.GetType()));
                var unexpectedTypes     = actualOutputs.Keys
                                          .Where(t => !expectedOutputTypes.Contains(t))
                                          .ToOrderedCsv();

                throw new AssertFailedException($"Unexpected captures: {unexpectedTypes}");
            }
        }
Exemplo n.º 36
0
 public void Construct()
 {
     _relay    = _componentBuilder.CreateRelay();
     _post     = _componentBuilder.CreatePost();
     _handler  = _componentBuilder.CreateHandler();
     _scenario = _componentBuilder.CreateScenario();
 }
Exemplo n.º 37
0
        public async Task FetchHandlerBasicTests(IScenario scenario)
        {
            // Arrange
            var siteRoot = @"x:\vdir0\site";
            var deploymentManager = new MockDeploymentManager();
            var fileSystem = GetFileSystem(siteRoot, scenario.WriteTimeUTCs.ToArray());
            var environment = GetEnvironment(siteRoot);
            var serviceHookHandler = GetServiceHookHandler();
            var repositoryFactory = GetRepositoryFactory();
            var handler = CreateFetchHandler(deploymentManager: deploymentManager,
                                             fileSystem: fileSystem.Object,
                                             serviceHookHandler: serviceHookHandler.Object,
                                             repositoryFactory: repositoryFactory.Object,
                                             environment: environment.Object);

            // Test
            await handler.PerformDeployment(new DeploymentInfo
            {
                IsReusable = scenario.IsReusable,
                Handler = serviceHookHandler.Object,
                TargetChangeset = GetChangeSet()
            });

            // Assert
            Assert.Equal(scenario.DeployCount, deploymentManager.DeployCount);
        }
Exemplo n.º 38
0
 private static void Run(IScenario s, IBus bus)
 {
     var sw = Stopwatch.StartNew();
     s.Run(bus, Console.Out);
     Console.WriteLine("Done in " + sw.Elapsed.TotalSeconds + " seconds");
     Console.WriteLine("--");
     s.Reset();
 }
 private void AddScenarioElement(IProject project, UnitTestElementConsumer consumer,
     StorEvilStoryElement storyElement, IScenario scenario)
 {
     if (scenario is Scenario)
         consumer(new StorEvilScenarioElement(_provider, storyElement, project, scenario.Name, (Scenario)scenario));
     else
         consumer(new StorEvilScenarioOutlineElement(_provider, storyElement, project, scenario.Name,
                                                     (ScenarioOutline)scenario));
 }
Exemplo n.º 40
0
        public async Task InitialCloneBasicTests(IScenario scenario)
        {
            // this contains zip files for each scenario
            using (var repo = Git.Clone("WebDeploySamples"))
            {
                string zipFile = Path.Combine(repo.PhysicalPath, scenario.Name + ".zip");
                Assert.True(File.Exists(zipFile), "Could not find " + zipFile);

                await ApplicationManager.RunAsync(scenario.Name, async appManager =>
                {
                    // moodle takes 5 mins to zip deploy (< 100s default timeout).
                    // appManager.ZipManager.Client.Timeout = TimeSpan.FromMinutes(10);

                    // deploy zip file using /zip
                    appManager.ZipManager.PutZipFile("site/wwwroot", zipFile);

                    // sanity validate content
                    scenario.DeployVerify(appManager.SiteUrl);

                    // simulate LocalGit env
                    // this is actually done at create site.
                    // however, the site reuse cleared this up.
                    await appManager.SettingsManager.SetValue(SettingsKeys.ScmType, "LocalGit");

                    // initial clone to temp folder
                    // this will clone from wwwroot
                    string repositoryPath = Git.CloneToLocal(appManager.GitUrl);

                    try
                    {
                        // we should have set the SCM_REPOSITORY_PATH to wwwroot
                        var value = await appManager.SettingsManager.GetValue(SettingsKeys.RepositoryPath);
                        Assert.Equal("wwwroot", value);

                        // make local modification
                        scenario.ApplyChange(repositoryPath);

                        // commit and push
                        Git.Commit(repositoryPath, "new change");
                        Git.Push(repositoryPath, appManager.GitUrl);

                        // validate deployment status
                        var results = (await appManager.DeploymentManager.GetResultsAsync()).ToList();
                        Assert.Equal(1, results.Count);
                        Assert.Equal(DeployStatus.Success, results[0].Status);

                        // validate changed content
                        scenario.ChangeVerify(appManager.SiteUrl);
                    }
                    finally
                    {
                        SafeExecute(() => Directory.Delete(repositoryPath, recursive: true));
                    }
                });
            }
        }
		/// <summary>Creates a new instance of the bot.</summary>
		public LostKeysUnited()
		{
			Logging.Setup();
			State = new GameState();
			Scenarios = new IScenario[]
			{
				Scenario.Defensive,
				Scenario.Default
			};
		}
 public StorEvilScenarioElement(StorEvilTestProvider provider, UnitTestElement parent, IProject project,
     string title, Scenario scenario)
     : base(provider, parent, project, title)
 {
     var root = project.Location.ToDirectoryInfo().FullName;
     var pathPieces = PathHelper.GetRelativePathPieces(root, scenario.Location.Path);
     var pathJoined = project.Name + " " + string.Join(" - ", pathPieces);
     _namespace = new UnitTestNamespace(pathJoined);
     Scenario = scenario;
 }
Exemplo n.º 43
0
        public IEnumerable<Scenario> Preprocess(IScenario scenario)
        {
            if (scenario is ScenarioOutline)
                return PreprocessExamples((ScenarioOutline) scenario).ToArray();

            if (scenario is Scenario)
                return new[] {(Scenario) scenario};

            throw new ArgumentOutOfRangeException("");
        }
Exemplo n.º 44
0
        public Story Execute(IScenario scenario)
        {
            if (scenario.Examples == null)
            {
                return scenario.BDDfy(scenario.Title);
            }

            return scenario
                    .WithExamples(scenario.Examples)
                    .BDDfy(scenario.Title);
        }
 public void Validate(IScenario scenario)
 {
     var lastEvent = scenario.PropertyEventMonitor.Dequeue();
     if (lastEvent == null)
     {
         Assert.Fail("Property changed event for property '{0}' was expected but was not raised.", _propertyName);
     }
     else if (lastEvent.Arguments.PropertyName != _propertyName)
     {
         Assert.Fail("Property changed event for property '{0}' was expected, but '{1}' was raised instead.", _propertyName, lastEvent.Arguments.PropertyName);
     }
 }
        private StoryMetadata CreateScenarioMetadata(IScenario scenario)
        {
            var storyAttribute = (StoryNarrativeAttribute)scenario.GetType()
                .GetCustomAttributes(typeof(StoryNarrativeAttribute), true)
                .FirstOrDefault();

            if (storyAttribute != null)
            {
                return new StoryMetadata(scenario.Story, storyAttribute);
            }

            var story = (Story)Activator.CreateInstance(scenario.Story);
            return new StoryMetadata(scenario.Story, story.Narrative1, story.Narrative2,
                story.Narrative3, story.Title, story.TitlePrefix);
        }
        private void OpenScenario(IScenario scenario)
        {
            if (scenario == null)
                return;

            // If it's a scenario group, open that group
            if (scenario is ScenarioGroup)
                base.Frame.Navigate(typeof(MainPage), scenario);

            // Otherwise if it's a atomic scenario, open the page for that
            else if (scenario is Scenario)
                base.Frame.Navigate(typeof(ScenarioPage), scenario);

            else
                throw new NotImplementedException("Unknown type of scenario");
        }
Exemplo n.º 48
0
        public void UsingMetadata(
            string text, IStepContext stepContext, IStep step, IScenario scenario, IXunitTestCase scenarioOutline)
        {
            "When I execute a step"
                .f(c => stepContext = c);

            "Then the step context contains metadata about the step"
                .f(() => (step = stepContext.Step.Should().NotBeNull().And.Subject.As<IStep>())
                    .DisplayName.Should().Be("Xbehave.Test.Acceptance.MetadataFeature.UsingMetadata(text: \"abc\") [01] When I execute a step"));

            "And the step contains metadata about the scenario"
                .f(() => (scenario = step.Scenario.Should().NotBeNull().And.Subject.As<IScenario>())
                    .DisplayName.Should().Be("Xbehave.Test.Acceptance.MetadataFeature.UsingMetadata(text: \"abc\")"));

            "And the step contains metadata about the scenario outline"
                .f(() => scenario.ScenarioOutline.Should().NotBeNull().And.Subject.As<IXunitTestCase>()
                    .DisplayName.Should().Be("Xbehave.Test.Acceptance.MetadataFeature.UsingMetadata"));
        }
Exemplo n.º 49
0
        public void Execute(IScenario testObject, string scenarioTitle = null)
        {
            using (var container = Configuration.ApplicationContainer.Resolve<IContainer>())
            {
                foreach (var action in Configuration.PerScenarioActions)
                {
                    action.Before(container);
                }

                var scenario = (IScenario)container.Resolve(testObject.GetType());
                scenario.SetContainer(container);
                _testEngine.Execute(scenario);

                foreach (var action in Configuration.PerScenarioActions.AsEnumerable().Reverse())
                {
                    action.After();
                }
            }
        }
        public ScenarioGroup FindParent(IScenario ofScenario)
        {
            foreach (var child in Children)
            {
                if (child == ofScenario)
                    return this;

                if (child is ScenarioGroup)
                {
                    ScenarioGroup recursiveFound = (child as ScenarioGroup).FindParent(ofScenario);
                    if (recursiveFound != null)
                        return recursiveFound;
                }
            }

            return null;


        }
Exemplo n.º 51
0
 private void AddScenarioElement(IProject project, UnitTestElementConsumer consumer,
     StorEvilStoryElement storyElement, IScenario scenario)
 {
     if (scenario is Scenario)
         consumer(new StorEvilScenarioElement(_provider, storyElement, project, scenario.Name, (Scenario)scenario));
     else
     {
         var outline = (ScenarioOutline) scenario;
         var outlineElement = new StorEvilScenarioOutlineElement(_provider, storyElement, project, scenario.Name,
                                                                                 outline);
         consumer(outlineElement);
         var i = 0;
         foreach (var child in new ScenarioPreprocessor().Preprocess(scenario))
         {
             consumer(new StorEvilScenarioElement(_provider, outlineElement, project, BuildExampleRowScenarioName(outline, i), child));
             i++;
         }
     }
 }
Exemplo n.º 52
0
        private IStorEvilJob GetJob(RemoteTask remoteTask, IScenario scenario)
        {
            _listener.SetCurrentTask(remoteTask);
            IStoryProvider provider = new SingleScenarioStoryProvider(scenario);

            return new StorEvilJob(provider, _runner);
        }
 private string GetBody(IScenario scenario)
 {
     if (scenario is Scenario)
         return GetScenarioBody((Scenario) scenario);
     return null;
 }
        public void CustomGitRepositoryHandlerBasic(IScenario scenario)
        {
            var headers = new System.Collections.Specialized.NameValueCollection();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var context = new Mock<HttpContextBase>();
            var environment = new Mock<IEnvironment>();
            var repositoryFactory = new Mock<IRepositoryFactory>();
            var repository = new Mock<IRepository>();
            repository.SetupGet(c => c.RepositoryType).Returns(RepositoryType.Git);
            repositoryFactory.Setup(c => c.GetCustomRepository())
                .Returns(scenario.RepositoryExists ? repository.Object : null);
            environment.SetupGet(c => c.RootPath).Returns(scenario.SiteRoot);
            environment.SetupProperty(c => c.RepositoryPath);
            request.SetupGet(c => c.Url).Returns(scenario.RequestUri);
            request.SetupGet(c => c.Headers).Returns(headers);
            response.SetupGet(c => c.OutputStream).Returns(new System.IO.MemoryStream());
            response.SetupProperty(c => c.StatusCode);
            context.SetupGet(c => c.Response).Returns(response.Object);
            context.SetupGet(c => c.Request).Returns(request.Object);

            CustomGitRepositoryHandler handler =
                CreateHandler(environment: environment.Object,
                              repositoryFactory: repositoryFactory.Object);

            handler.ProcessRequestBase(context.Object);
            scenario.Verify(environment.Object, (HttpStatusCode)response.Object.StatusCode);
        }
Exemplo n.º 55
0
 public void AddScenario(IScenario scenario)
 {
     scenarios.Add(scenario);
 }
        public void Validate(IScenario scenario)
        {
            if (scenario.BindableLinqQuery is IEnumerable == false) return;

            var lastEvent = scenario.CollectionEventMonitor.Dequeue();
            if (lastEvent != null)
            {
                CompareTo(lastEvent.Arguments);
            }
            else
            {
                CompareTo(null);
            }
        }
Exemplo n.º 57
0
 public void Validate(IScenario scenario)
 {
     var count = ((IBindableCollection)scenario.BindableLinqQuery).Count;
     Assert.AreEqual(_count, count);
 }
Exemplo n.º 58
0
 public bool Include(Story story, IScenario scenario)
 {
     return true;
 }
Exemplo n.º 59
0
 private IEnumerable<ScenarioLine> GetLines(IScenario scenario)
 {
     if (scenario is Scenario)
         return ((Scenario)scenario).Body;
     else
         return ((ScenarioOutline)scenario).Scenario.Body;
 }
        public bool Execute(CommandProcessorContext context, string[] args)
        {
            if (args.Length != 0 && false == (args.Length == 7 || args.Length == 8))
                return false;

            var maxConcurrentRequests = 20;
            var connections = 10;
            var streams = 100;
            var eventsPerStream = 400;
            var streamDeleteStep = 7;
            var scenarioName = "";
            var executionPeriodMinutes = 2;
            string dbParentPath = null;
            NodeConnectionInfo customNode = null;

            {
                if (args.Length == 9)
                {
                    throw new ArgumentException("Not compatible arguments, only one of <dbPath> or <custom node> can be specified.");
                }

                if (args.Length == 8)
                {
                    IPAddress ip;
                    int tcpPort;
                    int httpPort;

                    var atoms = args[7].Split(':');
                    if (atoms.Length == 3
                        && IPAddress.TryParse(atoms[0], out ip)
                        && int.TryParse(atoms[1], out tcpPort)
                        && int.TryParse(atoms[2], out httpPort))
                    {
                        customNode = new NodeConnectionInfo(ip, tcpPort, httpPort);

                        args = CutLastArgument(args);
                    }
                }

                if (args.Length == 7 || args.Length == 8)
                {
                    try
                    {
                        maxConcurrentRequests = int.Parse(args[0]);
                        connections = int.Parse(args[1]);
                        streams = int.Parse(args[2]);
                        eventsPerStream = int.Parse(args[3]);
                        streamDeleteStep = int.Parse(args[4]);
                        scenarioName = args[5];
                        executionPeriodMinutes = int.Parse(args[6]);

                        if (args.Length == 8)
                        {
                            dbParentPath = args[7];
                        }
                        else
                        {
                            var envDbPath = Environment.GetEnvironmentVariable("EVENTSTORE_DATABASEPATH");
                            if (!string.IsNullOrEmpty(envDbPath))
                                dbParentPath = envDbPath;
                        }

                    }
                    catch (Exception e)
                    {
                        Log.Error("Invalid arguments ({0})", e.Message);
                        return false;
                    }
                }
            }

            context.IsAsync();

            Log.Info("\n---" +
                     "\nRunning scenario {0} using {1} connections with {2} max concurrent requests," +
                     "\nfor {3} streams {4} events each deleting every {5}th stream. " +
                     "\nExecution period {6} minutes. " +
                     "\nDatabase path {7};" +
                     "\nCustom Node {8};" +
                     "\n---",
                     scenarioName,
                     connections,
                     maxConcurrentRequests,
                     streams,
                     eventsPerStream,
                     streamDeleteStep,
                     executionPeriodMinutes,
                     dbParentPath,
                     customNode);

            var directTcpSender = CreateDirectTcpSender(context);
            var allScenarios = new IScenario[]
            {
                new LoopingScenario(directTcpSender, 
                                    maxConcurrentRequests, 
                                    connections, 
                                    streams, 
                                    eventsPerStream, 
                                    streamDeleteStep, 
                                    TimeSpan.FromMinutes(executionPeriodMinutes),
                                    dbParentPath,
                                    customNode), 
                new ProjectionsKillScenario(directTcpSender,
                                            maxConcurrentRequests,
                                            connections,
                                            streams,
                                            eventsPerStream,
                                            streamDeleteStep, 
                                            dbParentPath,
                                            customNode),
                new ProjForeachForcedCommonNameScenario(directTcpSender,
                                            maxConcurrentRequests,
                                            connections,
                                            streams,
                                            eventsPerStream,
                                            streamDeleteStep,
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode),
                new ProjForeachForcedCommonNameNoRestartScenario (directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                new LoopingProjTranWriteScenario(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep,
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                new LoopingProjectionKillScenario(directTcpSender, 
                                                  maxConcurrentRequests, 
                                                  connections, 
                                                  streams, 
                                                  eventsPerStream, 
                                                  streamDeleteStep, 
                                                  TimeSpan.FromMinutes(executionPeriodMinutes),
                                                  dbParentPath,
                                                  customNode), 
                new MassProjectionsScenario(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            dbParentPath,
                                            customNode),
                new ProjectionWrongTagCheck(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                };

            Log.Info("Found scenarios {0} total :\n{1}.", allScenarios.Length, allScenarios.Aggregate(new StringBuilder(),
                                                                                                       (sb, s) => sb.AppendFormat("{0}, ", s.GetType().Name)));
            var scenarios = allScenarios.Where(x => scenarioName == AllScenariosFlag
                                                    || x.GetType().Name.Equals(scenarioName, StringComparison.InvariantCultureIgnoreCase))
                                        .ToArray();

            Log.Info("Running test scenarios ({0} total)...", scenarios.Length);

            foreach (var scenario in scenarios)
            {
                using (scenario)
                {
                    try
                    {
                        Log.Info("Run scenario {0}", scenario.GetType().Name);
                        scenario.Run();
                        scenario.Clean();
                        Log.Info("Scenario run successfully");
                    }
                    catch (Exception e)
                    {
                        context.Fail(e);
                    }
                }
            }
            Log.Info("Finished running test scenarios");

            if (context.ExitCode == 0)
                context.Success();

            return true;
        }