Example #1
0
        public bool Include(Story story, IScenario scenario)
        {
            if (_tags.Count() == 0)
                return true;

            return AnyTagMatches(story.Tags) || AnyTagMatches(scenario.Tags);
        }
        private Assembly BuildTestAssembly(Story story)
        {
            var generator = new NUnitFixtureGenerator();
            var code = generator.GenerateFixture(story, GetContext());

            return CreateTestAssembly(code);
        }
        public string GenerateFixture(Story story, StoryContext context)
        {
            var tests = new StringBuilder();

            var contextSet = new TestContextSet();
            IEnumerable<string> namespaces = new string[0];

            foreach (var scenario in story.Scenarios)
            {
                foreach (var s in _preprocessor.Preprocess(scenario))
                {
                    NUnitTest test = MethodGenerator.GetTestFromScenario(s, context);
                    tests.Append("        " + test.Body);
                    tests.AppendLine();
                    contextSet.AddRange(test.ContextTypes);
                    namespaces = namespaces.Union(test.Namespaces).Distinct();
                }
            }

            var usingStatements = namespaces.Select(x => string.Format("using {0};", x));
            var usings = string.Join("\r\n", usingStatements.ToArray());

            var writeStoryToConsole = "Console.WriteLine(@\"" + story.Summary.Replace("\"", "\"\"") + "\r\n" + " \");";
            const string ns = "StorEvilSpecifications";
            var categories = string.Join("", (story.Tags ?? new string[0]).Select(t => string.Format(@"[Category(""{0}"")]", t)).ToArray());
            return string.Format(FixtureFormat, ns, usings, GetFixtureName(story), tests, writeStoryToConsole, categories, story.Id);
        }
        bool FilterIncludes(string[] storyTags, string[] scenarioTags)
        {
            var scenario = new Scenario() {Tags = storyTags};
            var story = new Story("", "", new[] { scenario }) { Tags = scenarioTags };

            return Filter.Include(story, scenario);
        }
        private void AppendStoryCode(StringBuilder codeBuilder, Story story, Scenario[] scenarios)
        {
            var i = 0;
            foreach (var scenario in scenarios)
            {
                codeBuilder.AppendLine(@"
            scenario = scenarios[" + i + @"];

            using (StartScenario(story, scenario)) {

            #line 1  """ + story.Id + @"""
            #line hidden");
                foreach (var line in GetLines(scenario))
                {
                    codeBuilder.AppendFormat(@"
            if (ShouldContinue) {{
            #line {0}
            ExecuteLine(@""{1}"");
            #line hidden
            }}
            ", line.LineNumber, line.Text.Replace("\"", "\"\""));
                }
                codeBuilder.AppendLine("}");
                codeBuilder.AppendLine(@"CollectScenarioResult();");

                i++;
            }
        }
 public void StoryStarting(Story story)
 {
     _currentStoryElement = _doc.CreateElement(XmlNames.Story);
     _currentStoryElement.SetAttribute(XmlNames.Id, story.Id);
     _currentStoryElement.SetAttribute(XmlNames.Summary, story.Summary);
     SetStatus(_currentStoryElement, StatusNames.Success);
     _doc.DocumentElement.AppendChild(_currentStoryElement);
 }
        public string GetSourceCode(Story story, IEnumerable<Scenario> scenarios, IEnumerable<string> referencedAssemblies)
        {
            var codeBuilder = new StringBuilder();

            codeBuilder.AppendLine("// " + story.Id);
            AppendStoryCode(codeBuilder, story, scenarios.ToArray());

            return string.Format(_sourceCodeTemplate, "", BuildContextFactorySetup(referencedAssemblies), codeBuilder.ToString());
        }
        public void Should_Create_One_Test_For_A_Single_Scenario()
        {
            var s = BuildScenario("foo", new[] {"When I Do Something"});
            var story = new Story("foobar", "summary", new[] {s});

            Assembly a = BuildTestAssembly(story);
            var fixture = a.GetTypes()[0];
            fixture.GetTestMethods().Count().ShouldEqual(1);
        }
        public void Should_name_class_after_id()
        {
            var s = BuildScenario("test", new[] { "When I Do Something" });
            var story = new Story("C:\\Example\\Path\\To\\File.feature", "summary", new[] { s });

            Assembly a = BuildTestAssembly(story);
            var fixture = a.GetTypes()[0];
            fixture.Name.ShouldContain("Example_Path_To_File");
        }
        private void AddStoryElement(Story story, IProject project,
            UnitTestElementConsumer consumer, StorEvilProjectElement parent)
        {
            var storyElement = GetStoryElement(parent, project, story);
            consumer(storyElement);

            foreach (IScenario scenario in story.Scenarios)
                AddScenarioElement(project, consumer, storyElement, scenario);
        }
 protected override void Execute(Story story, IEnumerable<Scenario> scenarios, StoryContext context)
 {
     using (var remoteHandler = _factory.GetHandler(story, scenarios, ResultListener))
     {
         var handler = remoteHandler.Handler;
         handler.HandleStory(story);
         Result += handler.GetResult();
     }
 }
 private void AddScenarios(Story story, StringBuilder stringBuilder)
 {
     foreach (var scenario in story.Scenarios)
     {
         var name = scenario.Name.ToCSharpMethodName();
         stringBuilder.AppendLine("  [NUnit.Framework.TestAttribute] public void " + name + "() {");
         stringBuilder.AppendFormat("#line 1  \"{0}\"\r\n#line hidden\r\n", story.Id);
         stringBuilder.AppendLine(GetBody(scenario) +  "  }");
     }
 }
Example #13
0
        public void Invokes_Handler_For_Single_Story_And_Context()
        {
            var story = new Story("test context", "summary", new List<IScenario>());

            var job = GetJobWithMockDependencies();

            job.StoryProvider.Stub(x => x.GetStories()).Return(new[] {story});
            StubHandleStoriesReturn(job, new JobResult {});
            job.Run();
            job.Handler.AssertWasCalled(x => x.HandleStories( new [] {story}));
        }
        public void Should_have_category_for_each_tag_on_story()
        {
            var scenario = BuildScenario("test", new[] { "When I Do Something" });
            var s = new Story("foo", "summary", new Scenario[] { scenario }) { Tags = new[] { "foo", "bar" } };
            Assembly a = BuildTestAssembly(s);
            var testClass = a.GetTypes().First(x=>x.GetCustomAttributes(typeof(TestFixtureAttribute), true).Any());
            var attributes = testClass
                .GetCustomAttributes(typeof (CategoryAttribute), true)
                .Cast<CategoryAttribute>()
                .Select(x=>x.Name);

            attributes.OrderBy(x=>x).ElementsShouldEqual("bar", "foo");
        }
        public void HandleStory(Story story)
        {
            EventBus.Raise(new StoryStarting {Story = story});

            Scenario[] scenariosMatchingFilter = GetScenariosMatchingFilter(story);

            using (StoryContext contextForStory = _context.GetContextForStory())
            {
                Execute(story, scenariosMatchingFilter, contextForStory);
            }

            EventBus.Raise(new StoryFinished { Story = story });
        }
        protected override void Execute(Story story, IEnumerable<Scenario> scenariosMatchingFilter, StoryContext context)
        {
            int failed = 0;
            foreach (var scenario in scenariosMatchingFilter)
            {
                using (var scenarioContext = context.GetScenarioContext())
                {
                    if (!_scenarioRunner.ExecuteScenario(scenario, scenarioContext))
                        failed++;
                }
            }

            Result.Failed = Result.Failed + failed;
        }
Example #17
0
 public void HandleStory(Story story)
 {
     var context = _context.GetContextForStory();
     foreach (var scenario in story.Scenarios)
     {
         var scenarioContext = context .GetScenarioContext();
         foreach (var line in GetLines(scenario))
         {
             if (null == _scenarioInterpreter.GetChain(scenarioContext, line))
             {
                 var suggestedCode = _implementationHelper.Suggest(line) + "\r\n";
                 AddSuggestion(suggestedCode);
             }
         }
     }
 }
        public string Generate(Story story, string defaultNamespace)
        {
            var stringBuilder = new StringBuilder();
            string fixtureName = GetFixtureName(story);
            stringBuilder.Append("namespace " + defaultNamespace + "{");
            var categories = string.Join("", (story.Tags ?? new string[0]).Select(t => string.Format(@"[Category(""{0}"")]", t)).ToArray());
            stringBuilder.AppendLine(categories);

            stringBuilder.Append("\r\n[NUnit.Framework.TestFixtureAttribute] public class " + fixtureName + " : StorEvil.CodeGeneration.TestFixture {\r\n ");
            stringBuilder.Append("  public object Contexts { get { return base.GetContexts();}}");
            AddLifecycleHandlers(stringBuilder);

            AddScenarios(story, stringBuilder);
            stringBuilder.Append("  }\r\n}");

            return stringBuilder.ToString();
        }
        public void SetupContext()
        {
            FakeWriter = MockRepository.GenerateMock<ITextWriter>();

            Generator =
                new StubGenerator(new ScenarioInterpreter(new InterpreterForTypeFactory(new ExtensionMethodHandler())),
                                  new ImplementationHelper(), FakeWriter, new FakeStoryContextFactory());

            TestStory = new Story("foo", "", new[]
                                                 {
                                                      TestHelper.BuildScenario("", new[] { "first line", "second line" }),
                                                      TestHelper.BuildScenario("", new[] { "first line", "second line", "third line" }),
                                                      TestHelper.BuildScenario("", new[] { "this line's weird, punctuation! should be: handled"})
                                                 });

            Generator.HandleStory(TestStory);
            Generator.Finished();

            Suggestions = (string) FakeWriter.GetArgumentsForCallsMadeOn(x => x.Write(Arg<string>.Is.Anything))[0][0];
        }
        public void SetupContext()
        {
            FakeWriter = MockRepository.GenerateMock<ITextWriter>();
            FakeResolver = MockRepository.GenerateMock<IAmbiguousMatchResolver>();

            var scenarioInterpreter = new ScenarioInterpreter(new InterpreterForTypeFactory(new AssemblyRegistry()), FakeResolver, new DefaultLanguageService());
            Generator =
                new StubGenerator(scenarioInterpreter,
                                  new ImplementationHelper(), FakeWriter, new FakeSessionContext());

            TestStory = new Story("foo", "", new[]
                                                 {
                                                      TestHelper.BuildScenario("", new[] { "first line", "second line" }),
                                                      TestHelper.BuildScenario("", new[] { "first line", "second line", "third line" }),
                                                      TestHelper.BuildScenario("", new[] { "this line's weird, punctuation! should be: handled"})
                                                 });

            Generator.HandleStories(new[] {TestStory});

            Suggestions = (string) FakeWriter.GetArgumentsForCallsMadeOn(x => x.Write(Arg<string>.Is.Anything))[0][0];
        }
 public void SetupContext()
 {
     Result = new StoryParser().Parse(testOutlineTableStoryText, null);
 }
        public void SetupContext()
        {
            var parser = new StoryParser();

            Result = parser.Parse(testBackgroundText, "C:\\foo\\bar.feature");
        }
 public void StoryStarting(Story story)
 {
     DoWrite(ConsoleColor.White, "\r\n" + "\r\nSTORY: " + story.Id + "\r\n" + story.Summary);
 }
 public JobResult HandleStories(Story[] stories)
 {
     Handler.HandleStories(stories);
     Handler.Finished();
     return Handler.GetResult();
 }
Example #25
0
 public bool Include(Story story, IScenario scenario)
 {
     return true;
 }
 protected void SimulateStoryStarting(Story story)
 {
     Writer.Handle(new StoryStarting { Story = story });
 }
 public void Should_Contain_A_Single_testFixture_for_a_Story()
 {
     var s = new Story("test", "summary", new Scenario[] {});
     Assembly a = BuildTestAssembly(s);
     a.GetTypes().Length.ShouldEqual(1);
 }
 public void Should_Compile_When_No_Scenarios()
 {
     var s = new Story("test", "summary", new Scenario[] {});
     Assembly a = BuildTestAssembly(s);
 }
 private string GetFixtureName(Story story)
 {
     if (!string.IsNullOrEmpty(story.Id))
         return story.Id.ToCSharpMethodName();
     return story.Summary.ToCSharpMethodName();
 }
 public void SetupContext()
 {
     var parser = new StoryParser();
     Result = parser.Parse(testSingleStoryText, null);
 }