public void ShouldProcessExecuteStepRequestForTableParam(Parameter.Types.ParameterType parameterType)
        {
            const string parsedStepText = "Foo";
            var          protoTable     = new  ProtoTable();
            var          headers        = new ProtoTableRow();

            headers.Cells.AddRange(new List <string> {
                "foo", "bar"
            });
            protoTable.Headers = headers;
            var row = new ProtoTableRow();

            row.Cells.AddRange(new List <string> {
                "foorow1", "foorow2"
            });
            protoTable.Rows.AddRange(new List <ProtoTableRow>()
            {
                row
            });

            var request = new Message()
            {
                MessageType        = Message.Types.MessageType.ExecuteStep,
                ExecuteStepRequest = new ExecuteStepRequest()
                {
                    ActualStepText = parsedStepText,
                    ParsedStepText = parsedStepText,
                    Parameters     =
                    {
                        new Parameter()
                        {
                            ParameterType = parameterType,
                            Table         = protoTable
                        }
                    },
                },
                MessageId = 20
            };

            var mockStepRegistry = new Mock <IStepRegistry>();

            mockStepRegistry.Setup(x => x.ContainsStep(parsedStepText)).Returns(true);
            var fooMethodInfo = new GaugeMethod {
                Name = "Foo", ParameterCount = 1
            };

            mockStepRegistry.Setup(x => x.MethodFor(parsedStepText)).Returns(fooMethodInfo);
            var mockMethodExecutor = new Mock <IMethodExecutor>();

            mockMethodExecutor.Setup(e => e.Execute(fooMethodInfo, It.IsAny <string[]>())).Returns(() => new ProtoExecutionResult()
            {
                ExecutionTime = 1,
                Failed        = false
            });

            var response = new ExecuteStepProcessor(mockStepRegistry.Object, mockMethodExecutor.Object).Process(request);

            mockMethodExecutor.Verify(executor => executor.Execute(fooMethodInfo, It.Is <string[]>(strings => HasTable(strings))));
            Assert.False(response.ExecutionStatusResponse.ExecutionResult.Failed);
        }
Ejemplo n.º 2
0
        public IEnumerable <string> GetStepTexts(GaugeMethod gaugeMethod)
        {
            var stepMethod = MethodMap[gaugeMethod.Name];

            return(stepMethod.GetCustomAttributes(_assemblyLoader.GetLibType(LibType.Step))
                   .SelectMany(x => x.GetType().GetProperty("Names").GetValue(x, null) as string[]));
        }
Ejemplo n.º 3
0
        public static RefactoringChange Refactor(GaugeMethod method, IList <Tuple <int, int> > parameterPositions,
                                                 IList <string> parameters, string newStepValue)
        {
            var tree        = CSharpSyntaxTree.ParseText(File.ReadAllText(method.FileName));
            var root        = tree.GetRoot();
            var stepMethods = from node in root.DescendantNodes().OfType <MethodDeclarationSyntax>()
                              let attributeSyntaxes = node.AttributeLists.SelectMany(syntax => syntax.Attributes)
                                                      let classDef = node.Parent as ClassDeclarationSyntax
                                                                     where string.CompareOrdinal(node.Identifier.ValueText, method.Name) == 0 &&
                                                                     string.CompareOrdinal(classDef.Identifier.ValueText, method.ClassName) == 0 &&
                                                                     attributeSyntaxes.Any(syntax =>
                                                                                           string.CompareOrdinal(syntax.ToFullString(), LibType.Step.FullName()) > 0)
                                                                     select node;

            var stepMethod = stepMethods.First();
            var stepSpan   = stepMethod.AttributeLists.WithStepAttribute().Attributes.GetStepAttribute()
                             .ArgumentList.Arguments.First().GetLocation().GetLineSpan();
            var paramsSpan        = stepMethod.ParameterList.GetLocation().GetLineSpan();
            var updatedAttribute  = ReplaceAttribute(stepMethod, newStepValue);
            var updatedParameters = ReplaceParameters(stepMethod, parameterPositions, parameters);
            var declarationSyntax = stepMethod
                                    .WithAttributeLists(updatedAttribute)
                                    .WithParameterList(updatedParameters);
            var replaceNode = root.ReplaceNode(stepMethod, declarationSyntax);
            var change      = new RefactoringChange
            {
                FileName    = method.FileName,
                Diffs       = new List <Diff>(),
                FileContent = replaceNode.ToFullString()
            };

            change.Diffs.Add(CreateDiff(stepSpan, $"\"{newStepValue}\""));
            change.Diffs.Add(CreateDiff(paramsSpan, updatedParameters.ToFullString().Trim()));
            return(change);
        }
Ejemplo n.º 4
0
 private void AddStepsToRegsitry(string fileName, IEnumerable <MethodDeclarationSyntax> stepMethods)
 {
     foreach (var stepMethod in stepMethods)
     {
         var attributeListSyntax = stepMethod.AttributeLists.WithStepAttribute();
         var attributeSyntax     = attributeListSyntax.Attributes.GetStepAttribute();
         var stepTextsSyntax     = attributeSyntax.ArgumentList.Arguments.ToList();
         var stepTexts           = stepTextsSyntax.Select(s => s.ToString().Trim('"'));
         var hasAlias            = stepTexts.Count() > 1;
         foreach (var stepText in stepTexts)
         {
             var stepValue = Regex.Replace(stepText, @"(<.*?>)", @"{}");
             var classDef  = stepMethod.Parent as ClassDeclarationSyntax;
             var entry     = new GaugeMethod
             {
                 Name           = stepMethod.Identifier.ValueText,
                 ParameterCount = stepMethod.ParameterList.Parameters.Count,
                 StepText       = stepText,
                 HasAlias       = hasAlias,
                 Aliases        = stepTexts,
                 StepValue      = stepValue,
                 Span           = stepMethod.GetLocation().GetLineSpan(),
                 ClassName      = classDef.Identifier.ValueText,
                 FileName       = fileName
             };
             _stepRegistry.AddStep(stepValue, entry);
         }
     }
 }
Ejemplo n.º 5
0
        public void ShouldTakeScreenShotUsingCustomScreenShotMethod()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod
            {
                Name           = "ShouldTakeScreenShotUsingCustomScreenShotMethod",
                ParameterCount = 1
            };

            var result = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, It.IsAny <string[]>())).Returns(result);

            byte[] bytes = { 0x20, 0x20 };
            mockSandBox.Setup(sandbox => sandbox.TryScreenCapture(out bytes)).Returns(true);

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, "Bar", "String");

            mockSandBox.VerifyAll();
            Assert.True(executionResult.Failed);
            Assert.True(executionResult.ScreenShot != null);
            Assert.AreEqual(2, executionResult.ScreenShot.Length);
        }
Ejemplo n.º 6
0
            public void ShouldProcessStepNameWithAliasRequest()
            {
                var mockStepRegistry = new Mock <IStepRegistry>();
                var request          = new StepNameRequest
                {
                    StepValue = "step1"
                };
                var          parsedStepText = request.StepValue;
                const string stepText       = "step1";

                mockStepRegistry.Setup(r => r.ContainsStep(parsedStepText)).Returns(true);
                mockStepRegistry.Setup(r => r.GetStepText(parsedStepText)).Returns(stepText);

                var gaugeMethod = new GaugeMethod
                {
                    FileName = "foo",
                    HasAlias = true,
                    Aliases  = new List <string> {
                        "step2", "step3"
                    }
                };

                mockStepRegistry.Setup(r => r.MethodFor(parsedStepText)).Returns(gaugeMethod);
                mockStepRegistry.Setup(r => r.HasAlias(stepText)).Returns(true);
                var stepNameProcessor = new StepNameProcessor(mockStepRegistry.Object);

                var response = stepNameProcessor.Process(request);

                Assert.AreEqual(response.FileName, "foo");
                Assert.AreEqual(response.StepName[0], "step2");
                Assert.AreEqual(response.StepName[1], "step3");
                Assert.True(response.HasAlias);
            }
Ejemplo n.º 7
0
        public IStepRegistry GetStepRegistry()
        {
            var infos    = GetMethods(LibType.Step);
            var registry = new StepRegistry();

            foreach (var info in infos)
            {
                var stepTexts = info.GetCustomAttributes(GetLibType(LibType.Step))
                                .SelectMany(x => x.GetType().GetProperty("Names").GetValue(x, null) as string[]);
                foreach (var stepText in stepTexts)
                {
                    var stepValue  = GetStepValue(stepText);
                    var hasAlias   = stepTexts.Count() > 1;
                    var stepMethod = new GaugeMethod
                    {
                        Name              = info.FullyQuallifiedName(),
                        ParameterCount    = info.GetParameters().Length,
                        StepText          = stepText,
                        HasAlias          = hasAlias,
                        Aliases           = stepTexts,
                        MethodInfo        = info,
                        ContinueOnFailure = info.IsRecoverableStep(this),
                        StepValue         = stepValue
                    };
                    registry.AddStep(stepValue, stepMethod);
                }
            }

            return(registry);
        }
Ejemplo n.º 8
0
        public void ShouldNotTakeScreenShotWhenDisabled()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldNotTakeScreenShotWhenDisabled", ParameterCount = 1
            };

            var result = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, It.IsAny <string[]>())).Returns(result);

            var screenshotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ON_FAILURE");

            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", "false");

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, "Bar", "String");

            mockSandBox.VerifyAll();
            Assert.False(executionResult.ScreenShot == null);
            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", screenshotEnabled);
        }
Ejemplo n.º 9
0
        public ProtoExecutionResult ExecuteStep(GaugeMethod method, params string[] args)
        {
            var stopwatch = Stopwatch.StartNew();
            var builder   = new ProtoExecutionResult
            {
                Failed = false
            };
            var executionResult = _stepExecutor.Execute(method, args);

            builder.ExecutionTime = stopwatch.ElapsedMilliseconds;
            if (executionResult.Success)
            {
                return(builder);
            }
            var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

            builder.Failed = true;
            var isScreenShotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ON_FAILURE");

            if (isScreenShotEnabled == null || isScreenShotEnabled.ToLower() != "false")
            {
                builder.ScreenShot = TakeScreenshot();
            }
            builder.ErrorMessage     = executionResult.ExceptionMessage;
            builder.StackTrace       = executionResult.StackTrace;
            builder.RecoverableError = executionResult.Recoverable;
            builder.ExecutionTime    = elapsedMilliseconds;

            return(builder);
        }
Ejemplo n.º 10
0
        public void ShouldExecuteMethod()
        {
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };
            var args = new[] { "Bar", "String" };

            var mockClassInstanceManager = new Mock <object>().Object;
            var mockReflectionWrapper    = new Mock <IReflectionWrapper>();
            var mockAssemblyLoader       = new Mock <IAssemblyLoader>();
            var mockActivationWrapper    = new Mock <IActivatorWrapper>();
            var mockHookExecuter         = new Mock <IHookExecutor>();
            var mockStepExecutor         = new Mock <IStepExecutor>();

            mockStepExecutor.Setup(executor => executor.Execute(gaugeMethod, It.IsAny <string[]>()))
            .Returns(() => new ExecutionResult {
                Success = true
            })
            .Callback(() => Thread.Sleep(1));     // Simulate a delay in method execution

            var orchestrator = new ExecutionOrchestrator(mockReflectionWrapper.Object, mockAssemblyLoader.Object,
                                                         mockActivationWrapper.Object, mockClassInstanceManager,
                                                         mockHookExecuter.Object, mockStepExecutor.Object);
            var result = orchestrator.ExecuteStep(gaugeMethod, args);

            mockStepExecutor.VerifyAll();
            Assert.False(result.Failed);
            Assert.True(result.ExecutionTime > 0);
        }
Ejemplo n.º 11
0
            public void ShouldProcessExternalSteps()
            {
                var mockStepRegistry = new Mock <IStepRegistry>();
                var request          = new StepNameRequest
                {
                    StepValue = "step1"
                };
                var          parsedStepText = request.StepValue;
                const string stepText       = "step1";

                mockStepRegistry.Setup(r => r.ContainsStep(parsedStepText)).Returns(true);
                mockStepRegistry.Setup(r => r.GetStepText(parsedStepText)).Returns(stepText);

                var gaugeMethod = new GaugeMethod
                {
                    FileName   = "foo",
                    IsExternal = true
                };

                mockStepRegistry.Setup(r => r.MethodFor(parsedStepText)).Returns(gaugeMethod);
                var stepNameProcessor = new StepNameProcessor(mockStepRegistry.Object);

                var response = stepNameProcessor.Process(request);

                Assert.True(response.IsExternal);
                // Assert.AreEqual(response.FileName, null);
            }
Ejemplo n.º 12
0
        public static string Refactor(GaugeMethod method, IList <Tuple <int, int> > parameterPositions,
                                      IList <string> parameters, string newStepValue)
        {
            var changedFile = "";

            var tree        = CSharpSyntaxTree.ParseText(File.ReadAllText(method.FileName));
            var root        = tree.GetRoot();
            var stepMethods = from node in root.DescendantNodes().OfType <MethodDeclarationSyntax>()
                              let attributeSyntaxes = node.AttributeLists.SelectMany(syntax => syntax.Attributes)
                                                      let classDef = node.Parent as ClassDeclarationSyntax
                                                                     where string.CompareOrdinal(node.Identifier.ValueText, method.Name) == 0 &&
                                                                     string.CompareOrdinal(classDef.Identifier.ValueText, method.ClassName) == 0 &&
                                                                     attributeSyntaxes.Any(syntax =>
                                                                                           string.CompareOrdinal(syntax.ToFullString(), LibType.Step.FullName()) > 0)
                                                                     select node;

            //TODO: check for aliases and error out
            foreach (var methodDeclarationSyntax in stepMethods)
            {
                var updatedAttribute  = ReplaceAttribute(methodDeclarationSyntax, newStepValue);
                var updatedParameters = ReplaceParameters(methodDeclarationSyntax, parameterPositions, parameters);
                var declarationSyntax = methodDeclarationSyntax
                                        .WithAttributeLists(updatedAttribute)
                                        .WithParameterList(updatedParameters);
                var replaceNode = root.ReplaceNode(methodDeclarationSyntax, declarationSyntax);

                File.WriteAllText(method.FileName, replaceNode.ToFullString());
                changedFile = method.FileName;
            }

            return(changedFile);
        }
        public void ShouldReportArgumentMismatch()
        {
            const string parsedStepText = "Foo";
            var          request        = new Message
            {
                MessageType        = Message.Types.MessageType.ExecuteStep,
                MessageId          = 20,
                ExecuteStepRequest = new ExecuteStepRequest
                {
                    ActualStepText = parsedStepText,
                    ParsedStepText = parsedStepText
                }
            };
            var mockStepRegistry = new Mock <IStepRegistry>();

            mockStepRegistry.Setup(x => x.ContainsStep(parsedStepText)).Returns(true);
            var fooMethod = new GaugeMethod {
                Name = "Foo", ParameterCount = 1
            };

            mockStepRegistry.Setup(x => x.MethodFor(parsedStepText)).Returns(fooMethod);
            var mockOrchestrator = new Mock <IExecutionOrchestrator>();

            var mockTableFormatter = new Mock <ITableFormatter>();

            var response =
                new ExecuteStepProcessor(mockStepRegistry.Object, mockOrchestrator.Object, mockTableFormatter.Object)
                .Process(request);

            Assert.True(response.ExecutionStatusResponse.ExecutionResult.Failed);
            Assert.AreEqual(response.ExecutionStatusResponse.ExecutionResult.ErrorMessage,
                            "Argument length mismatch for Foo. Actual Count: 0, Expected Count: 1");
        }
Ejemplo n.º 14
0
        public ProtoExecutionResult ExecuteStep(GaugeMethod method, params string[] args)
        {
            var stopwatch = Stopwatch.StartNew();

            var executionResult = _stepExecutor.Execute(method, args);

            return(BuildResult(stopwatch, executionResult));
        }
Ejemplo n.º 15
0
        public IEnumerable <string> GetStepTexts(GaugeMethod gaugeMethod)
        {
            const string fullStepName = "Gauge.CSharp.Lib.Attribute.Step";
            var          stepMethod   = MethodMap[gaugeMethod.Name];
            dynamic      step         = stepMethod.GetCustomAttributes()
                                        .FirstOrDefault(a => a.GetType().FullName.Equals(fullStepName));

            return(step.Names);
        }
        public void ShouldProcessExecuteStepRequestForTableParam(Parameter.Types.ParameterType parameterType)
        {
            const string parsedStepText = "Foo";
            var          protoTable     = new ProtoTable();
            var          tableJSON      = "{'headers':['foo', 'bar'],'rows':[['foorow1','barrow1']]}";
            var          request        = new Message
            {
                MessageType        = Message.Types.MessageType.ExecuteStep,
                ExecuteStepRequest = new ExecuteStepRequest
                {
                    ActualStepText = parsedStepText,
                    ParsedStepText = parsedStepText,
                    Parameters     =
                    {
                        new Parameter
                        {
                            ParameterType = parameterType,
                            Table         = protoTable
                        }
                    }
                },
                MessageId = 20
            };

            var mockStepRegistry = new Mock <IStepRegistry>();

            mockStepRegistry.Setup(x => x.ContainsStep(parsedStepText)).Returns(true);
            var fooMethodInfo = new GaugeMethod {
                Name = "Foo", ParameterCount = 1
            };

            mockStepRegistry.Setup(x => x.MethodFor(parsedStepText)).Returns(fooMethodInfo);
            var mockOrchestrator = new Mock <IExecutionOrchestrator>();

            mockOrchestrator.Setup(e => e.ExecuteStep(fooMethodInfo, It.IsAny <string[]>())).Returns(() =>
                                                                                                     new ProtoExecutionResult
            {
                ExecutionTime = 1,
                Failed        = false
            });

            var mockAssemblyLoader = new Mock <IAssemblyLoader>();

            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.MessageCollector));
            var mockTableFormatter = new Mock <ITableFormatter>();

            mockTableFormatter.Setup(x => x.GetJSON(protoTable))
            .Returns(tableJSON);
            var response =
                new ExecuteStepProcessor(mockStepRegistry.Object, mockOrchestrator.Object, mockTableFormatter.Object)
                .Process(request);

            mockOrchestrator.Verify(executor =>
                                    executor.ExecuteStep(fooMethodInfo, It.Is <string[]>(strings => strings[0] == tableJSON)));
            Assert.False(response.ExecutionStatusResponse.ExecutionResult.Failed);
        }
        public void ShouldRefactorAttributeText()
        {
            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringContext",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };
            var changes = RefactorHelper.Refactor(gaugeMethod, new List <Tuple <int, int> >(), new List <string>(), "foo");

            AssertStepAttributeWithTextExists(changes, gaugeMethod.Name, "foo");
        }
        public void ShouldNotTakeScreenShotWhenDisabled()
        {
            var pendingMessages = new List <string> {
                "Foo", "Bar"
            };
            var pendingScrennshots = new List <byte[]> {
                Encoding.ASCII.GetBytes("screenshot")
            };
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldNotTakeScreenShotWhenDisabled", ParameterCount = 1
            };

            var executionResult = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };
            var mockClassInstanceManager = new Mock <object>().Object;
            var mockReflectionWrapper    = new Mock <IReflectionWrapper>();
            var mockAssemblyLoader       = new Mock <IAssemblyLoader>();
            var mockActivationWrapper    = new Mock <IActivatorWrapper>();
            var mockHookExecuter         = new Mock <IHookExecutor>();
            var mockStepExecutor         = new Mock <IStepExecutor>();

            mockStepExecutor.Setup(executor => executor.Execute(gaugeMethod, It.IsAny <string[]>()))
            .Returns(executionResult);
            var mockType = new Mock <Type>().Object;

            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.MessageCollector)).Returns(mockType);
            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.ScreenshotCollector)).Returns(mockType);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingMessages", It.IsAny <BindingFlags>()))
            .Returns(pendingMessages);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingScreenshots", It.IsAny <BindingFlags>()))
            .Returns(pendingScrennshots);

            var orchestrator = new ExecutionOrchestrator(mockReflectionWrapper.Object, mockAssemblyLoader.Object,
                                                         mockActivationWrapper.Object, mockClassInstanceManager,
                                                         mockHookExecuter.Object, mockStepExecutor.Object);

            var screenshotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ON_FAILURE");

            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", "false");

            var result = orchestrator.ExecuteStep(gaugeMethod, "Bar", "string");

            mockStepExecutor.VerifyAll();
            Assert.True(result.FailureScreenshot.IsNullOrEmpty());
            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", screenshotEnabled);
        }
        public void ShouldTakeScreenShotOnFailedExecution()
        {
            var pendingMessages = new List <string> {
                "Foo", "Bar"
            };
            var expectedScreenshot = "Testscreenshot.png";
            var pendingScreenshots = new List <string> {
                expectedScreenshot
            };
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };
            var executionResult = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "error",
                StackTrace       = "stacktrace"
            };
            var mockInstance          = new Mock <object>().Object;
            var mockAssemblyLoader    = new Mock <IAssemblyLoader>();
            var mockActivationWrapper = new Mock <IActivatorWrapper>();
            var mockReflectionWrapper = new Mock <IReflectionWrapper>();
            var mockHookExecuter      = new Mock <IHookExecutor>();
            var mockStepExecutor      = new Mock <IStepExecutor>();

            mockStepExecutor.Setup(executor => executor.Execute(gaugeMethod, It.IsAny <string[]>()))
            .Returns(executionResult).Verifiable();
            var mockType = new Mock <Type>().Object;

            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.MessageCollector)).Returns(mockType);
            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.ScreenshotFilesCollector)).Returns(mockType);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingMessages", It.IsAny <BindingFlags>()))
            .Returns(pendingMessages);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingScreenshotFiles", It.IsAny <BindingFlags>()))
            .Returns(pendingScreenshots);

            var orchestrator = new ExecutionOrchestrator(mockReflectionWrapper.Object, mockAssemblyLoader.Object,
                                                         mockActivationWrapper.Object, mockInstance,
                                                         mockHookExecuter.Object, mockStepExecutor.Object);

            var result = orchestrator.ExecuteStep(gaugeMethod, "Bar", "String");

            mockStepExecutor.VerifyAll();


            Assert.True(result.Failed);
            Assert.AreEqual(expectedScreenshot, result.FailureScreenshotFile);
        }
        public void ShouldRemoveParameters()
        {
            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringSaySomething",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };
            var parameterPositions = new[] { new Tuple <int, int>(0, 0) };

            var changes = RefactorHelper.Refactor(gaugeMethod, parameterPositions, new List <string>(),
                                                  "Refactoring Say <what> to someone");

            AssertParametersExist(changes, gaugeMethod.Name, new[] { "what" });
        }
Ejemplo n.º 21
0
        public void ShouldTakeScreenShotOnFailedExecution()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, "Bar")).Throws <Exception>();

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, "Bar", "String");

            mockSandBox.VerifyAll();
            Assert.True(executionResult.Failed);
            Assert.True(executionResult.ScreenShot != null);
            Assert.True(executionResult.ScreenShot.Length > 0);
        }
        public void ShouldRefactorAndReturnFilesChanged()
        {
            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringContext",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };

            var expectedPath = Path.GetFullPath(Path.Combine(_testProjectPath, "RefactoringSample.cs"));

            var changes =
                RefactorHelper.Refactor(gaugeMethod, new List <Tuple <int, int> >(), new List <string>(), "foo");

            Assert.AreEqual(expectedPath, changes.FileName);
        }
Ejemplo n.º 23
0
        public void ShouldRemoveParametersInAnyOrder()
        {
            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringSaySomething",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };

            var parameterPositions = new[] { new Tuple <int, int>(1, 0) };

            RefactorHelper.Refactor(gaugeMethod, parameterPositions, new List <string>(),
                                    "Refactoring Say something to <who>");

            AssertParametersExist(gaugeMethod.Name, new[] { "who" });
        }
Ejemplo n.º 24
0
        public void ShouldTakeScreenShotOnFailedExecution()
        {
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };
            var executionResult = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "error",
                StackTrace       = "stacktrace"
            };
            var expectedScreenshot = Encoding.UTF8.GetBytes("TestScreenshot");

            var type               = new Mock <Type>().Object;
            var mockInstance       = new Mock <object>().Object;
            var mockAssemblyLoader = new Mock <IAssemblyLoader>();

            mockAssemblyLoader.Setup(x => x.ScreengrabberType).Returns(type);

            var mockActivationWrapper = new Mock <IActivatorWrapper>();

            mockActivationWrapper.Setup(x => x.CreateInstance(type)).Returns(mockInstance);

            var mockReflectionWrapper = new Mock <IReflectionWrapper>();

            mockReflectionWrapper
            .Setup(x => x.InvokeMethod(type, mockInstance, "TakeScreenShot"))
            .Returns(expectedScreenshot);

            var mockHookExecuter = new Mock <IHookExecutor>();
            var mockStepExecutor = new Mock <IStepExecutor>();

            mockStepExecutor.Setup(executor => executor.Execute(gaugeMethod, It.IsAny <string[]>()))
            .Returns(executionResult).Verifiable();

            var orchestrator = new ExecutionOrchestrator(mockReflectionWrapper.Object, mockAssemblyLoader.Object,
                                                         mockActivationWrapper.Object, mockInstance,
                                                         mockHookExecuter.Object, mockStepExecutor.Object);

            var result = orchestrator.ExecuteStep(gaugeMethod, "Bar", "String");

            mockStepExecutor.VerifyAll();

            Assert.True(result.Failed);
            Assert.AreEqual(expectedScreenshot, result.ScreenShot);
        }
        public void ShouldExecuteMethod()
        {
            var pendingMessages = new List <string> {
                "Foo", "Bar"
            };
            var pendingScrennshots = new List <byte[]> {
                Encoding.ASCII.GetBytes("screenshot")
            };
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };
            var args = new[] { "Bar", "String" };

            var mockClassInstanceManager = new Mock <object>().Object;
            var mockReflectionWrapper    = new Mock <IReflectionWrapper>();
            var mockAssemblyLoader       = new Mock <IAssemblyLoader>();
            var mockActivationWrapper    = new Mock <IActivatorWrapper>();
            var mockHookExecuter         = new Mock <IHookExecutor>();
            var mockStepExecutor         = new Mock <IStepExecutor>();

            mockStepExecutor.Setup(executor => executor.Execute(gaugeMethod, It.IsAny <string[]>()))
            .Returns(() => new ExecutionResult {
                Success = true
            })
            .Callback(() => Thread.Sleep(1));     // Simulate a delay in method execution

            var orchestrator = new ExecutionOrchestrator(mockReflectionWrapper.Object, mockAssemblyLoader.Object,
                                                         mockActivationWrapper.Object, mockClassInstanceManager,
                                                         mockHookExecuter.Object, mockStepExecutor.Object);

            var mockType = new Mock <Type>().Object;

            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.MessageCollector)).Returns(mockType);
            mockAssemblyLoader.Setup(x => x.GetLibType(LibType.ScreenshotCollector)).Returns(mockType);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingMessages", It.IsAny <BindingFlags>()))
            .Returns(pendingMessages);
            mockReflectionWrapper.Setup(x =>
                                        x.InvokeMethod(mockType, null, "GetAllPendingScreenshots", It.IsAny <BindingFlags>()))
            .Returns(pendingScrennshots);
            var result = orchestrator.ExecuteStep(gaugeMethod, args);

            mockStepExecutor.VerifyAll();
            Assert.False(result.Failed);
            Assert.True(result.ExecutionTime > 0);
        }
        public void ShouldProcessExecuteStepRequest()
        {
            const string parsedStepText = "Foo";
            var          request        = new Message
            {
                MessageType        = Message.Types.MessageType.ExecuteStep,
                MessageId          = 20,
                ExecuteStepRequest = new ExecuteStepRequest
                {
                    ActualStepText = parsedStepText,
                    ParsedStepText = parsedStepText,
                    Parameters     =
                    {
                        new Parameter
                        {
                            ParameterType = Parameter.Types.ParameterType.Static,
                            Name          = "Foo",
                            Value         = "Bar"
                        }
                    }
                }
            };
            var mockStepRegistry = new Mock <IStepRegistry>();

            mockStepRegistry.Setup(x => x.ContainsStep(parsedStepText)).Returns(true);
            var fooMethodInfo = new GaugeMethod {
                Name = "Foo", ParameterCount = 1
            };

            mockStepRegistry.Setup(x => x.MethodFor(parsedStepText)).Returns(fooMethodInfo);
            var mockOrchestrator = new Mock <IExecutionOrchestrator>();

            mockOrchestrator.Setup(e => e.ExecuteStep(fooMethodInfo, It.IsAny <string[]>()))
            .Returns(() => new ProtoExecutionResult {
                ExecutionTime = 1, Failed = false
            });

            var mockTableFormatter = new Mock <ITableFormatter>();

            var response =
                new ExecuteStepProcessor(mockStepRegistry.Object, mockOrchestrator.Object, mockTableFormatter.Object)
                .Process(request);

            Assert.False(response.ExecutionStatusResponse.ExecutionResult.Failed);
        }
Ejemplo n.º 27
0
        public void ShouldAddParametersWhenNoneExisted()
        {
            const string newStepValue = "Refactoring this is a test step <foo>";
            var          gaugeMethod  = new GaugeMethod
            {
                Name      = "RefactoringSampleTest",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };
            var parameterPositions = new[] { new Tuple <int, int>(-1, 0) };

            RefactorHelper.Refactor(gaugeMethod, parameterPositions, new List <string> {
                "foo"
            }, newStepValue);

            AssertStepAttributeWithTextExists(gaugeMethod.Name, newStepValue);
            AssertParametersExist(gaugeMethod.Name, new[] { "foo" });
        }
        public void ShouldAddParametersWithReservedKeywordName()
        {
            const string newStepValue = "Refactoring this is a test step <class>";

            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringSampleTest",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };
            var parameterPositions = new[] { new Tuple <int, int>(-1, 0) };

            var changes = RefactorHelper.Refactor(gaugeMethod, parameterPositions, new List <string> {
                "class"
            },
                                                  newStepValue);

            AssertStepAttributeWithTextExists(changes, gaugeMethod.Name, newStepValue);
            AssertParametersExist(changes, gaugeMethod.Name, new[] { "@class" });
        }
Ejemplo n.º 29
0
        public void ShouldExecuteMethod()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldExecuteMethod", ParameterCount = 1
            };
            var args = new[] { "Bar", "String" };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, It.IsAny <string[]>()))
            .Returns(() => new ExecutionResult {
                Success = true
            })
            .Callback(() => Thread.Sleep(1));     // Simulate a delay in method execution

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, args);

            mockSandBox.VerifyAll();
            Assert.False(executionResult.Failed);
            Assert.True(executionResult.ExecutionTime > 0);
        }
Ejemplo n.º 30
0
        public void ShouldReorderParameters()
        {
            const string newStepValue = "Refactoring Say <who> to <what>";

            var gaugeMethod = new GaugeMethod
            {
                Name      = "RefactoringSaySomething",
                ClassName = "RefactoringSample",
                FileName  = Path.Combine(_testProjectPath, "RefactoringSample.cs")
            };

            var parameterPositions = new[] { new Tuple <int, int>(0, 1), new Tuple <int, int>(1, 0) };

            RefactorHelper.Refactor(gaugeMethod, parameterPositions, new List <string> {
                "who", "what"
            }, newStepValue);

            AssertStepAttributeWithTextExists(gaugeMethod.Name, newStepValue);
            AssertParametersExist(gaugeMethod.Name, new[] { "who", "what" });
        }