Ejemplo n.º 1
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            if (ConfigurationHelpers.ShouldBeProfiling())
            {
                builder.Register((c, p) => new TextReporter(p.TypedAs <Func <Stream> >()))
                .As <TextReporter>()
                .As <ITransformReports>();

                builder.Register(c => new TimingStorage())
                .OnRelease(
                    storage =>
                {
                    // Write all the profiling results out to disk. Do this the ugly way
                    // because we don't know if any of the other items in the container have
                    // been removed yet.
                    Func <Stream> factory =
                        () => new FileStream(
                            Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                            FileMode.Append,
                            FileAccess.Write,
                            FileShare.Read);
                    var reporter = new TextReporter(factory);
                    reporter.Transform(storage.FromStartTillEnd());
                })
                .As <IStoreIntervals>()
                .As <IGenerateTimingReports>()
                .SingleInstance();

                builder.Register(c => new Profiler(
                                     c.Resolve <IStoreIntervals>()))
                .SingleInstance();
            }
        }
        static void Main(string[] args)
        {
            var parser = new CsvParser();
            var config = BuildConfiguration();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var encoding = EncodingDetector.GetEncoding(config["data-file-path"]);
            var data     = parser.ParseFile(config["data-file-path"], encoding);

            if (parser.ErrorMessage != null)
            {
                Console.WriteLine("Parsing failed");
                Console.WriteLine(parser.ErrorMessage);
            }

            var report = DataAnalyser.Analyze(data, Convert.ToUInt32(config["min-number-for-adv-stat"]));

            using (var stream = new FileStream("report.txt", FileMode.Create))
            {
                TextReporter.ToStream(stream, report);
            }
            var reporter = new ExcelReport.ExcelReporter();

            using (var stream = new FileStream("report.xlsx", FileMode.Create))
            {
                reporter.ToStream(stream, report);
            }
        }
Ejemplo n.º 3
0
        public void OneVulnerability()
        {
            var reporter = new TextReporter(_consoleWrapper.Object);

            reporter.Start();
            reporter.Report(new Vulnerability
            {
                Code               = "ExampleCode",
                Title              = "Example Vulnerability",
                SeverityLevel      = SeverityLevel.Critical,
                Description        = "Description here.",
                FilePath           = "C:\\Program.cs",
                FullyQualifiedName = "Namespace.Class",
                LineNumber         = 10
            });
            reporter.Finish();

            Assert.AreEqual(@"Code: ExampleCode
Title: Example Vulnerability
SeverityLevel: Critical
Description: Description here.
File path: C:\Program.cs
Fully qualified name: Namespace.Class
Line number: 10

Total vulnerabilities: 1
".NormalizeEndOfLine(), _output.ToString());
        }
Ejemplo n.º 4
0
        private void MainForm_Load(object sender, EventArgs e) {
            hasRun = false;
            textReporter = new TextReporter(progressText);
            foreach (string argument in arguments) {
                textReporter.Write(string.Format("{0} ", argument));
            }
            textReporter.Write(Environment.NewLine);

        }
Ejemplo n.º 5
0
 void MainForm_Load(object sender, EventArgs e)
 {
     hasRun       = false;
     textReporter = new TextReporter(progressText);
     foreach (var argument in arguments)
     {
         textReporter.Write(string.Format("{0} ", argument));
     }
     textReporter.Write(Environment.NewLine);
 }
Ejemplo n.º 6
0
        public void NoVulnerabilities()
        {
            var reporter = new TextReporter(_consoleWrapper.Object);

            reporter.Start();
            reporter.Finish();

            Assert.AreEqual(@"Total vulnerabilities: 0
".NormalizeEndOfLine(), _output.ToString());
        }
Ejemplo n.º 7
0
        public void should_display_examples_on_reports()
        {
            var scenario = new StubUserStoryScenarioForWithExamples();
            var sut      = new BddfyTestEngine();

            var story = sut.Execute(scenario);

            var reporter = new TextReporter();

            reporter.Process(story);
            Approvals.Verify(reporter.ToString());
        }
Ejemplo n.º 8
0
        public void TagsAreReportedInTextReport()
        {
            var story = this.Given(_ => GivenAStep())
                        .WithTags("Tag1", "Tag 2")
                        .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);

            textReporter.ToString().ShouldMatchApproved();
        }
        public void FluentCanBeUsedWithExamples()
        {
            var story = this
                        .Given(_ => MethodTaking__ExampleIntA__(1), false)
                        .When(_ => WhenEmptyMethod())
                        .Then(_ => ThenAllIsGood())
                        .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);
            textReporter.ToString().ShouldMatchApproved();
        }
        public void FluentCanBeUsedWithExamplesEndingInANumber()
        {
            var story = this
                        .Given(_ => MethodTaking__ExampleInt1__(1), false)
                        .When(_ => WhenEmptyMethod())
                        .Then(_ => ThenAllIsGood())
                        .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);
            Approvals.Verify(textReporter.ToString());
        }
Ejemplo n.º 11
0
        public void ShouldProduceExpectedReport()
        {
            var stories = new ReportTestData().CreateMixContainingEachTypeOfOutcomeWithOneScenarioPerStory();
            var actual  = new StringBuilder();

            foreach (var story in stories)
            {
                var textReporter = new TextReporter();
                textReporter.Process(story);
                actual.AppendLine(textReporter.ToString());
            }

            Approvals.Verify(actual.ToString(), StackTraceScrubber.Scrub);
        }
Ejemplo n.º 12
0
        public void ShouldProduceExpectedTextWithExamples()
        {
            var stories = new ReportTestData().CreateTwoStoriesEachWithOneFailingScenarioAndOnePassingScenarioWithThreeStepsOfFiveMillisecondsAndEachHasTwoExamples();
            var actual  = new StringBuilder();

            foreach (var story in stories)
            {
                var textReporter = new TextReporter();
                textReporter.Process(story);
                actual.AppendLine(textReporter.ToString());
            }

            Approvals.Verify(actual.ToString(), StackTraceScrubber.Scrub);
        }
Ejemplo n.º 13
0
        public void Run()
        {
            var story = this
                        .WithExamples(new ExampleTable("First Example", "Second Example")
            {
                { 1, "foo" },
                { 2, "bar" }
            })
                        .BDDfy();

            var reporter = new TextReporter();

            reporter.Process(story);
            reporter.ToString().ShouldMatchApproved();
        }
Ejemplo n.º 14
0
        public void Inline()
        {
            // ReSharper disable once ConvertToConstant.Local
            var inlineVariable = 0;
            var story          = this
                                 .Given(_ => GivenIntWithValue(inlineVariable))
                                 .WithExamples(new ExampleTable("Inline Variable")
            {
                1, 2
            })
                                 .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);
            Approvals.Verify(textReporter.ToString());
        }
Ejemplo n.º 15
0
        public void VerifyPrependStepTitles()
        {
            var story = this.Given(_ => GivenAStepWithGivenInIt())
                        .Given(_ => AStepWithoutGivenInIt())
                        .And(_ => AndGivenAStepWithAndGivenInIt())
                        .And(_ => AStepWithoutGivenInIt())
                        .But(_ => ButInStep())
                        .But(_ => NothingInStep())
                        .When(_ => WhenStuff())
                        .When(_ => Stuff())
                        .Then(_ => ThenWeAreWinning())
                        .Then(_ => WeAreWinning())
                        .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);
            textReporter.ToString().ShouldMatchApproved();
        }
Ejemplo n.º 16
0
        public void LongStepName()
        {
            var textReporter = new TextReporter();
            var scenario     = new Scenario(typeof(TextReporterTests), new List <Step>
            {
                new Step(o => null, new StepTitle("Given a normal length title"), false, ExecutionOrder.SetupState, true, new List <StepArgument>()),
                new Step(o => null, new StepTitle("When something of normal length happens"), false, ExecutionOrder.Transition, true, new List <StepArgument>()),
                new Step(o => null, new StepTitle("Then some long state should be: #Title\r\n\r\nSome more stuff which is quite long on the second line\r\n\r\nAnd finally another really long line"),
                         true, ExecutionOrder.Assertion, true, new List <StepArgument>()),
                new Step(o => null, new StepTitle("And a normal length assertion"), true, ExecutionOrder.ConsecutiveAssertion, true, new List <StepArgument>())
            }, "Scenario Text", new List <string>());

            textReporter.Process(new Story(new StoryMetadata(typeof(TextReporterTests), new StoryNarrativeAttribute()),
                                           scenario));
            var actual = new StringBuilder();

            actual.AppendLine(textReporter.ToString());
            Approvals.Verify(actual.ToString(), StackTraceScrubber.Scrub);
        }
Ejemplo n.º 17
0
        public void CanUseActionsInExamples()
        {
            ExampleAction actionToPerform = null;
            int           valueShouldBe   = 0;
            var           story           = this.Given(_ => SomeSetup())
                                            .When(() => actionToPerform)
                                            .Then(_ => ShouldBe(valueShouldBe))
                                            .WithExamples(new ExampleTable("Action to perform", "Value should be")
            {
                { new ExampleAction("Do something", () => { _value = 42; }), 42 },
                { new ExampleAction("Do something else", () => { _value = 7; }), 7 }
            })
                                            .BDDfy();


            var textReporter = new TextReporter();

            textReporter.Process(story);
            textReporter.ToString().ShouldMatchApproved();
        }
Ejemplo n.º 18
0
        public void TextReporterTest()
        {
            using (var stream = new MemoryStream())
            {
                TextReporter.ToStream(stream, _dataAnalyserReport);

                using (var readableStream = new MemoryStream(stream.ToArray()))
                {
                    using (var reader = new StreamReader(readableStream))
                    {
                        var text = _textReporterOutput.Split(Environment.NewLine);
                        var i    = 0;
                        while (!reader.EndOfStream)
                        {
                            Assert.Equal(text[i++], reader.ReadLine());
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public void ToReport()
        {
            var group       = new TimingGroup();
            var description = "description";
            var ticks       = 10L;

            var interval = new Mock <ITimerInterval>();
            {
                interval.Setup(i => i.Group)
                .Returns(group);
                interval.Setup(i => i.Description)
                .Returns(description);
                interval.Setup(i => i.TotalTicks)
                .Returns(ticks);
            }

            var           path    = TempFile();
            Func <Stream> builder = () => new FileStream(path, FileMode.Create, FileAccess.Write);

            var reporter = new TextReporter(builder);

            var tree = new TimingTree();

            tree.AddBaseInterval(interval.Object);

            var report = new TimingReport(tree);

            reporter.Transform(report);

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var result = FromStream(stream);
                Assert.AreEqual(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Description    Total time (ms)" + Environment.NewLine + "{0}    {1}" + Environment.NewLine,
                        description,
                        ticks / 10000),
                    result);
            }
        }
Ejemplo n.º 20
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            try
            {
                var value = ConfigurationManager.AppSettings[LoadProfilerAppSetting];

                bool result;
                if (bool.TryParse(value, out result) && result)
                {
                    // Only register the storage and the profiler because we won't be writing out
                    // intermediate results here anyway. No point in registering report converters
                    builder.Register(c => new TimingStorage())
                    .OnRelease(
                        storage =>
                    {
                        // Write all the profiling results out to disk. Do this the ugly way
                        // because we don't know if any of the other items in the container have
                        // been removed yet.
                        Func <Stream> factory =
                            () => new FileStream(
                                Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                                FileMode.OpenOrCreate,
                                FileAccess.Write,
                                FileShare.Read);
                        var reporter = new TextReporter(factory);
                        reporter.Transform(storage.FromStartTillEnd());
                    })
                    .As <IStoreIntervals>();

                    builder.Register(c => new Profiler(
                                         c.Resolve <IStoreIntervals>()));
                }
            }
            catch (ConfigurationErrorsException)
            {
                // could not retrieve the AppSetting from the config file
                // meh ...
            }
        }
Ejemplo n.º 21
0
        public void FluentCanBeUsedWithExamples()
        {
            var story = this
                        .Given(_ => MethodTaking__ExampleInt__(Prop1), false)
                        .And(_ => MethodTaking__ExampleInt__(_.Prop1), false)
                        .And(_ => ADifferentMethodWithRandomArg(2))
                        .And(_ => ADifferentMethodWith(_prop2))
                        .When(_ => WhenMethodUsing__ExampleString__())
                        .And(_ => AndIUseA(multiWordHeading))
                        .Then(_ => ThenAllIsGood())
                        .WithExamples(new ExampleTable("Prop 1", "Prop2", "Prop 3", "Multi word heading")
            {
                { 1, "foo", ExecutionOrder.ConsecutiveAssertion, "" },
                { 2, "bar", ExecutionOrder.Initialize, "val2" }
            })
                        .BDDfy();

            var textReporter = new TextReporter();

            textReporter.Process(story);
            Approvals.Verify(textReporter.ToString());
        }
Ejemplo n.º 22
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            if (ConfigurationHelpers.ShouldBeProfiling())
            {
                builder.Register((c, p) => new TextReporter(p.TypedAs<Func<Stream>>()))
                        .As<TextReporter>()
                        .As<ITransformReports>();

                builder.Register(c => new TimingStorage())
                    .OnRelease(
                        storage =>
                        {
                            // Write all the profiling results out to disk. Do this the ugly way
                            // because we don't know if any of the other items in the container have
                            // been removed yet.
                            Func<Stream> factory =
                                () => new FileStream(
                                    Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                                    FileMode.Append,
                                    FileAccess.Write,
                                    FileShare.Read);
                            var reporter = new TextReporter(factory);
                            reporter.Transform(storage.FromStartTillEnd());
                        })
                    .As<IStoreIntervals>()
                    .As<IGenerateTimingReports>()
                    .SingleInstance();

                builder.Register(c => new Profiler(
                        c.Resolve<IStoreIntervals>()))
                    .SingleInstance();
            }
        }
Ejemplo n.º 23
0
        public void ToReportWithMultiLevelIntervals()
        {
            var ticks = 10L;

            var group  = new TimingGroup();
            var parent = new Mock <ITimerInterval>();
            {
                parent.Setup(i => i.Group)
                .Returns(group);
                parent.Setup(i => i.Description)
                .Returns("parent");
                parent.Setup(i => i.TotalTicks)
                .Returns(ticks);
            }

            var child1 = new Mock <ITimerInterval>();
            {
                child1.Setup(i => i.Group)
                .Returns(group);
                child1.Setup(i => i.Description)
                .Returns("child1");
                child1.Setup(i => i.TotalTicks)
                .Returns(ticks);
            }

            var child2 = new Mock <ITimerInterval>();
            {
                child2.Setup(i => i.Group)
                .Returns(group);
                child2.Setup(i => i.Description)
                .Returns("child2");
                child2.Setup(i => i.TotalTicks)
                .Returns(ticks);
            }

            var           path    = TempFile();
            Func <Stream> builder = () => new FileStream(path, FileMode.Create, FileAccess.Write);

            var reporter = new TextReporter(builder);

            var tree = new TimingTree();

            tree.AddBaseInterval(parent.Object);
            tree.AddChildInterval(parent.Object, child1.Object);
            tree.AddChildInterval(parent.Object, child2.Object);

            var report = new TimingReport(tree);

            reporter.Transform(report);

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var result      = FromStream(stream);
                var textBuilder = new StringBuilder();
                {
                    textBuilder.AppendLine("Description   Total time (ms)");
                    textBuilder.AppendLine(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "{0}        {1}",
                            parent.Object.Description,
                            ticks / 10000));
                    textBuilder.AppendLine(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "    {0}      {1}",
                            child1.Object.Description,
                            ticks / 10000));
                    textBuilder.AppendLine(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "    {0}      {1}",
                            child2.Object.Description,
                            ticks / 10000));
                }

                Assert.AreEqual(textBuilder.ToString(), result);
            }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            InitGlobalizationEngine(Language.EN);

            Model   model  = new Model();
            Device  device = model.CreateDevice("Master");
            SMQueue queue  = model.CreateQueue("Accumulator");

            UInt64 transactCounter = 1;

            model.Schedule((int)Events.EventGenerate, model.Random(14, 26), transactCounter);
            model.Schedule((int)Events.EventEnd, 480, (ulong)1e9);

            // Объявим переменную, в которой будем хранить номер текущего транзакта
            UInt64 transact = 1;
            // И переменную, в которй будем хранить тип текущего события
            Events @event = Events.EventEnd;

            do
            {
                (UInt64, UInt64)top = model.Cause();
                // Разбираем пару на отдельные составляющие
                @event   = (Events)top.Item1;
                transact = top.Item2;

                switch (@event)
                {
                // Алгоритм обработки события порождения заявки
                case Events.EventGenerate:
                {
                    // Планируем сразу же событие резервирования устройства за этой заявкой
                    model.Schedule((int)Events.EventReserve, 0, transact);
                    // Увеличиваем счетчик транзактов
                    transactCounter++;
                    // Планируем поступление следующией заявки
                    model.Schedule((int)Events.EventGenerate, model.Random(14, 26), transactCounter);
                    break;
                }

                case Events.EventReserve:
                {
                    if (device.GetState() == Device.State.Idle)
                    {
                        // В случае, если устройство свободно, займем его заявкой
                        device.Reserve(transact);
                        // Запланируем освобождение устройства
                        model.Schedule((int)Events.EventRelease, model.Random(12, 20), transact);
                    }
                    else
                    {
                        queue.Add(transact, 0);
                    }

                    break;
                }

                case Events.EventRelease:
                {
                    device.Release();
                    if (queue.Count > 0)
                    {
                        UInt64 transactId = queue.Dequeue(out UInt64 stage).TransactId;
                        model.Schedule((int)Events.EventReserve, 0, transactId);
                    }

                    break;
                }

                case Events.EventEnd:
                {
                    break;
                }

                default:
                {
                    throw new Exception();
                }
                }
            }while (@event != Events.EventEnd);

            TextReporter textReporter = new TextReporter(model);

            textReporter.GetReport("output.txt");

            using (MdReporter mdReporter = new MdReporter(model))
            {
                mdReporter.GetReport("output.md");
            }

            using (HtmlReporter htmlReporter = new HtmlReporter(model))
            {
                htmlReporter.GetReport("output.html");
            }
        }
Ejemplo n.º 25
0
        private static void RegisterProfiler(ContainerBuilder builder)
        {
            try
            {
                var value = ConfigurationManager.AppSettings[LoadProfilerAppSetting];

                bool result;
                if (bool.TryParse(value, out result) && result)
                {
                    // Only register the storage and the profiler because we won't be writing out
                    // intermediate results here anyway. No point in registering report converters
                    builder.Register(c => new TimingStorage())
                        .OnRelease(
                            storage =>
                            {
                                // Write all the profiling results out to disk. Do this the ugly way
                                // because we don't know if any of the other items in the container have
                                // been removed yet.
                                Func<Stream> factory =
                                    () => new FileStream(
                                        Path.Combine(FileConstants.LogPath(), DefaultProfilerFileName),
                                        FileMode.OpenOrCreate,
                                        FileAccess.Write,
                                        FileShare.Read);
                                var reporter = new TextReporter(factory);
                                reporter.Transform(storage.FromStartTillEnd());
                            })
                        .As<IStoreIntervals>();

                    builder.Register(c => new Profiler(
                            c.Resolve<IStoreIntervals>()));
                }
            }
            catch (ConfigurationErrorsException)
            {
                // could not retrieve the AppSetting from the config file
                // meh ...
            }
        }