コード例 #1
0
        public async Task OneTimeSetUp()
        {
            TestSetUp.Reset(false);

            _robotTest = new RobotTest();
            await _robotTest.OneTimeSetUp();
        }
コード例 #2
0
ファイル: TesterBase.cs プロジェクト: mtikoian/Beef
        /// <summary>
        /// Prepares the <see cref="ExecutionContext"/> using the <see cref="TestSetUpAttribute"/> configuration, whilst also ensuring that the <see cref="LocalServiceProvider"/> scope is correctly configured.
        /// </summary>
        public void PrepareExecutionContext()
        {
            ExecutionContext.Reset();
            var ec = TestSetUp.CreateExecutionContext(TestSetUpAttribute.Username, TestSetUpAttribute.Args);

            ec.ServiceProvider = LocalServiceProvider;
            ExecutionContext.SetCurrent(ec);
        }
コード例 #3
0
ファイル: TesterBase.cs プロジェクト: mtikoian/Beef
        /// <summary>
        /// Prepares the <see cref="ExecutionContext"/> using the specified <paramref name="username"/>, whilst also ensuring that the <see cref="LocalServiceProvider"/> scope is correctly configured.
        /// </summary>
        /// <param name="username">The username (<c>null</c> indicates to use the <see cref="TestSetUp.DefaultUsername"/>).</param>
        /// <param name="args">Optional argument that will be passed into the creation of the <see cref="ExecutionContext"/> (via the <see cref="TestSetUp.CreateExecutionContext"/> function).</param>
        /// <returns>The <see cref="AgentTesterWaf{TStartup}"/> instance to support fluent/chaining usage.</returns>
        /// <remarks>The <see cref="ExecutionContext"/> must be created by the <see cref="AgentTesterBase"/> as the <see cref="ExecutionContext.ServiceProvider"/> must be set to <see cref="LocalServiceProvider"/>.</remarks>
        public void PrepareExecutionContext(string?username, object?args = null)
        {
            ExecutionContext.Reset();
            var ec = TestSetUp.CreateExecutionContext(username ?? TestSetUp.DefaultUsername, args);

            ec.ServiceProvider = LocalServiceProvider;
            ExecutionContext.SetCurrent(ec);
        }
コード例 #4
0
        public void Ctor_NoIEventSubscriber()
        {
            var sp = TestSetUp.CreateServiceProvider();

            ExpectException.Throws <ArgumentException>("*", () => EventSubscriberHostArgs.Create(sp));
            ExpectException.Throws <ArgumentException>("*", () => EventSubscriberHostArgs.Create(sp, (Type[])null));
            ExpectException.Throws <ArgumentException>("*", () => EventSubscriberHostArgs.Create(sp, new Type[] { }));
        }
コード例 #5
0
        public void OneTimeSetUp()
        {
            TestSetUp.Reset();

            AgentTester.Create <PersonAgent, Person>()
            .ExpectStatusCode(HttpStatusCode.NotFound)
            .Run((a) => a.Agent.GetAsync(404.ToGuid()));
        }
コード例 #6
0
        public void C120_DoNotAllowMultipleMessages()
        {
            var sp = TestSetUp.CreateServiceProvider();

            ExpectException.Throws<EventSubscriberException>(
                "The 'EventDataSubscriberHost' does not AllowMultipleMessages; there were 2 event messages.",
                async () => await new EventDataSubscriberHost(EventSubscriberHostArgs.Create(typeof(TestSub)).UseServiceProvider(sp).UseLoggerForAuditing()).ReceiveAsync(new EventData(), new EventData()));
        }
コード例 #7
0
 public async Task C130_AllowMultipleMessages()
 {
     await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), new TestSub()).UseLoggerForAuditing()).AllowMultipleMessages().ReceiveAsync(new EventData {
         Subject = "X"
     }, new EventData {
         Subject = "X"
     });
 }
コード例 #8
0
        public void OneTimeSetUp()
        {
            TestSetUp.RegisterSetUp(async(count, _) =>
            {
                // Setup and load cosmos once only.
                if (count == 0)
                {
                    var config      = AgentTester.Configuration.GetSection("CosmosDb");
                    _removeAfterUse = config.GetValue <bool>("RemoveAfterUse");
                    _cosmosDb       = new CosmosDb(new Cosmos.CosmosClient(config.GetValue <string>("EndPoint"), config.GetValue <string>("AuthKey")),
                                                   config.GetValue <string>("Database"), createDatabaseIfNotExists: true);

                    var ac = await _cosmosDb.ReplaceOrCreateContainerAsync(
                        new Cosmos.ContainerProperties
                    {
                        Id = "Account",
                        PartitionKeyPath = "/_partitionKey"
                    }, 400).ConfigureAwait(false);

                    await ac.ImportBatchAsync <AccountTest, Business.Data.Model.Account>("Account.yaml", "Account").ConfigureAwait(false);

                    var tc = await _cosmosDb.ReplaceOrCreateContainerAsync(
                        new Cosmos.ContainerProperties
                    {
                        Id = "Transaction",
                        PartitionKeyPath = "/accountId"
                    }, 400).ConfigureAwait(false);

                    await tc.ImportBatchAsync <AccountTest, Business.Data.Model.Transaction>("Transaction.yaml", "Transaction").ConfigureAwait(false);

                    var rdc = await _cosmosDb.ReplaceOrCreateContainerAsync(
                        new Cosmos.ContainerProperties
                    {
                        Id = "RefData",
                        PartitionKeyPath = "/_partitionKey",
                        UniqueKeyPolicy  = new Cosmos.UniqueKeyPolicy {
                            UniqueKeys = { new Cosmos.UniqueKey {
                                               Paths =          { "/type","/value/code" }
                                           } }
                        }
                    }, 400).ConfigureAwait(false);

                    await rdc.ImportValueRefDataBatchAsync <AccountTest>(ReferenceData.Current, "RefData.yaml").ConfigureAwait(false);
                }

                return(true);
            });

            AgentTester.StartupTestServer <Startup>(environmentVariablesPrefix: "Banking_");
            AgentTester.DefaultExpectNoEvents = true;

            // TODO: Passing the username as an http header for all requests; this would be replaced with OAuth integration, etc.
            AgentTester.RegisterBeforeRequest(r => r.Headers.Add("cdr-user", Beef.ExecutionContext.Current.Username));

            // Set "page" and "page-size" as the supported paging query string parameters as defined by the CDR specification.
            WebApiPagingArgsArg.PagingArgsPageQueryStringName = "page";
            WebApiPagingArgsArg.PagingArgsSizeQueryStringName = "page-size";
        }
コード例 #9
0
ファイル: ExpectEvent.cs プロジェクト: ostat/Beef
        /// <summary>
        /// Verify/compare expected versus sent.
        /// </summary>
        private static void AreSentCompare(List <ExpectedEvent> expectedEvents, string?correlationId, string testText, string expectText, string actualText, string checkText)
        {
            if (expectedEvents == null)
            {
                throw new ArgumentNullException(nameof(expectedEvents));
            }

            var actualEvents = GetSentEvents(correlationId);

            if (actualEvents.Count != expectedEvents.Count)
            {
                Assert.Fail($"{testText} {expectedEvents.Count} Event(s) {checkText} {expectText}; there were {actualEvents.Count} {actualText}.");
            }

            for (int i = 0; i < actualEvents.Count; i++)
            {
                // Assert subject and action.
                var exp = expectedEvents[i].EventData;
                var act = actualEvents[i];

                if (!EventSubjectMatcher.Match(_eventPublisher.TemplateWildcard, _eventPublisher.PathSeparator, exp.Subject, act.Subject))
                {
                    Assert.Fail($"{testText} {expectText} Event[{i}].Subject '{exp.Subject}' is not equal to actual '{act.Subject}' {actualText}.");
                }

                if (!string.IsNullOrEmpty(exp.Action) && string.CompareOrdinal(exp.Action, act.Action) != 0)
                {
                    Assert.Fail($"{testText} {expectText} Event[{i}].Action '{exp.Action}' is not equal to actual '{act.Action}' {actualText}.");
                }

                // Where there is *no* expected value then skip value comparison.
                if (!exp.HasValue)
                {
                    continue;
                }

                // Assert value.
                var eVal = exp.GetValue();
                var aVal = act.GetValue();

                var comparisonConfig = TestSetUp.GetDefaultComparisonConfig();
                comparisonConfig.AttributesToIgnore.AddRange(new Type[] { typeof(ReferenceDataInterfaceAttribute) });

                var type = eVal?.GetType() ?? aVal?.GetType();
                if (type != null)
                {
                    TestSetUp.InferAdditionalMembersToIgnore(comparisonConfig, type);
                }

                var cl = new CompareLogic(comparisonConfig);
                var cr = cl.Compare(eVal, aVal);
                if (!cr.AreEqual)
                {
                    Assert.Fail($"{testText} {expectText} Event[{i}].Value is not equal to actual {actualText}: {cr.DifferencesString}");
                }
            }
        }
コード例 #10
0
        public void Ctor_SubscribersInAssembly()
        {
            var args = new EventSubscriberHostArgs(TestSetUp.CreateLogger(), this.GetType().Assembly);

            Assert.AreEqual(2, args.EventSubscribers.Count());

            args = new EventSubscriberHostArgs(TestSetUp.CreateLogger());
            Assert.AreEqual(2, args.EventSubscribers.Count());
        }
コード例 #11
0
        public void C110_TooManySubjectSubscribers()
        {
            var ed = new EventData<string> { Subject = "Test.Blah.123", Action = "CREATE", Username = "******", Value = "TEST" };
            var sp = TestSetUp.CreateServiceProvider();

            ExpectException.Throws<EventSubscriberException>(
                "There are 2 IEventSubscriber instances subscribing to Subject 'Test.Blah.123' and Action 'CREATE'; there must be only a single subscriber.",
                async () => await new EventDataSubscriberHost(EventSubscriberHostArgs.Create(typeof(TestSub), typeof(TestSubS)).UseServiceProvider(sp).UseLoggerForAuditing()).ReceiveAsync(ed));
        }
コード例 #12
0
        public async Task B120_Unknown_Action()
        {
            var ts = new TestSubS();
            var ed = new EventData <string> {
                Subject = "Test.Blah.123", Action = "OTHER", Username = "******", Value = "TEST"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts).UseLoggerForAuditing()).ReceiveAsync(ed);

            Assert.IsFalse(ts.MessageReceived);
        }
コード例 #13
0
        public async Task C130_AllowMultipleMessages()
        {
            var sp = TestSetUp.CreateServiceProvider();

            await new EventDataSubscriberHost(EventSubscriberHostArgs.Create(sp, typeof(TestSub)).UseLoggerForAuditing()).AllowMultipleMessages().ReceiveAsync(new EventData {
                Subject = "X"
            }, new EventData {
                Subject = "X"
            });
        }
コード例 #14
0
        public async Task A150_Receive_OK_ExceptionContinue()
        {
            var ts = new TestSub(@throw: true, unhandledExceptionHandling: UnhandledExceptionHandling.Continue);
            var ed = new EventData {
                Subject = "Test.Blah.123", Action = "UPDATE", Username = "******"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts).UseLoggerForAuditing()).ReceiveAsync(ed);

            Assert.IsTrue(ts.MessageReceived);
        }
コード例 #15
0
ファイル: WebSuites.cs プロジェクト: NagKothapalli/Avijit
 public void BeforeTestRun()
 {
     configData = new Read_ConfigData();
     testData   = new Read_TestData(configData.root.webRunSttings.Environment);
     objRepo    = new Read_ObjectRepo();
     //Read config details , decide env , browser
     webDriver = TestSetUp.GetWebDriver();
     testCases = new TestCases();
     //appDriver = TestSetUp.GetAppiumDriver();
 }
コード例 #16
0
        public async Task A120_Unknown_Action()
        {
            var ts = new TestSub();
            var ed = new EventData {
                Subject = "Test.Blah.123", Action = "OTHER", Username = "******"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts)).ReceiveAsync(ed);

            Assert.IsFalse(ts.MessageReceived);
        }
コード例 #17
0
        public async Task A110_Unknown_Subject()
        {
            var ts = new TestSub();
            var ed = new EventData {
                Subject = "Other.Something", Action = "CREATE", Username = "******"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts).UseLoggerForAuditing()).ReceiveAsync(ed);

            Assert.IsFalse(ts.MessageReceived);
        }
コード例 #18
0
ファイル: TesterBase.cs プロジェクト: mtikoian/Beef
        /// <summary>
        /// Initializes a new instance of the <see cref="AgentTesterBase"/> class.
        /// </summary>
        /// <param name="configureLocalRefData">Indicates whether the pre-set local <see cref="TestSetUp.SetDefaultLocalReferenceData{TRefService, TRefProvider, TRefAgentService, TRefAgent}">reference data</see> is configured.</param>
        protected TesterBase(bool configureLocalRefData = true)
        {
            _serviceCollection.AddLogging(configure => configure.AddTestContext());
            _serviceCollection.AddSingleton(_ => new CachePolicyManager());
            _serviceCollection.AddTransient <IWebApiAgentArgs, WebApiAgentArgs>();

            if (configureLocalRefData)
            {
                TestSetUp.ConfigureDefaultLocalReferenceData(_serviceCollection);
            }
        }
コード例 #19
0
        public async Task A130_Receive_OK_OriginatingUser()
        {
            var ts = new TestSub(RunAsUser.Originating);
            var ed = new EventData {
                Subject = "Test.Blah.123", Action = "CREATE", Username = "******"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts).UseLoggerForAuditing()).ReceiveAsync(ed);

            Assert.IsTrue(ts.MessageReceived);
            Assert.AreEqual("TestUser", ts.Username);
        }
コード例 #20
0
ファイル: PersonTest.cs プロジェクト: keithlemon/Beef
        public void A110_Validation_Null()
        {
            TestSetUp.CreateMock <IPersonData>();
            ExpectValidationException.Run(
                () => (new PersonManager()).CreateAsync(null),
                "Value is required.");

            ExpectValidationException.Run(
                () => (new PersonManager()).UpdateAsync(null, 1.ToGuid()),
                "Value is required.");
        }
コード例 #21
0
        public void OneTimeSetUp()
        {
            TestSetUp.RegisterSetUp((count, data) =>
            {
                return(DatabaseExecutor.Run(
                           count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData,
                           AgentTester.Configuration["ConnectionStrings:Database"],
                           typeof(DatabaseExecutor).Assembly, typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly()) == 0);
            });

            AgentTester.StartupTestServer <Startup>(environmentVariablesPrefix: "AppName_");
        }
コード例 #22
0
        public void OneTimeSetUp()
        {
            TestSetUp.RegisterSetUp(async(count, data) =>
            {
                return(await DatabaseExecutor.RunAsync(
                           count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData,
                           AgentTester.Configuration["ConnectionStrings:BeefDemo"],
                           typeof(DatabaseExecutor).Assembly, typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly()).ConfigureAwait(false) == 0);
            });

            AgentTester.StartupTestServer <Startup>(environmentVariablesPrefix: "Beef_");
        }
コード例 #23
0
        public async Task A140_Receive_OK_SystemUser()
        {
            EventSubscriberHost.SystemUsername = "******";
            var ts = new TestSub(RunAsUser.System);
            var ed = new EventData {
                Subject = "Test.Blah.123", Action = "CREATE", Username = "******"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts)).ReceiveAsync(ed);

            Assert.IsTrue(ts.MessageReceived);
            Assert.AreEqual("SystemUser", ts.Username);
        }
コード例 #24
0
ファイル: FixtureSetup.cs プロジェクト: mdesenfants/Beef
        public void OneTimeSetUp()
        {
            TestSetUp.RegisterSetUp(async(count, data) =>
            {
                return(await DatabaseExecutor.RunAsync(
                           count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData,
                           AgentTester.Configuration["ConnectionStrings:BeefDemo"], useBeefDbo: true,
                           typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly(), typeof(Beef.Demo.Abc.Database.Scripts).Assembly).ConfigureAwait(false) == 0);
            });

            AgentTester.TestServerStart <Startup>("Beef");
        }
コード例 #25
0
        public async Task B150_Receive_OK_ExceptionContinue()
        {
            var ts = new TestSubS(@throw: true, unhandledExceptionHandling: UnhandledExceptionHandling.Continue);
            var ed = new EventData <string> {
                Subject = "Test.Blah.123", Action = "CREATE", Username = "******", Value = "TEST"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts).UseLoggerForAuditing()).ReceiveAsync(ed);

            Assert.IsTrue(ts.MessageReceived);
            Assert.AreEqual("TEST", ts.Value);
            Assert.AreEqual(typeof(string), ts.ValueType);
        }
コード例 #26
0
ファイル: FixtureSetup.cs プロジェクト: mdesenfants/Beef
        public void OneTimeSetUp()
        {
            TestSetUp.RegisterSetUp(async(count, _) =>
            {
                return(await DatabaseExecutor.RunAsync(
                           count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData,
                           AgentTester.Configuration["ConnectionStrings:Database"], useBeefDbo: true,
                           typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly()).ConfigureAwait(false) == 0);
            });

            AgentTester.TestServerStart <Startup>("AppName");
            AgentTester.DefaultExpectNoEvents = true;
        }
コード例 #27
0
        public async Task B130_Receive_OK_OriginatingUser()
        {
            var ts = new TestSubS(RunAsUser.Originating);
            var ed = new EventData <string> {
                Subject = "Test.Blah.123", Action = "CREATE", Username = "******", Value = "TEST"
            };
            await EventDataSubscriberHost.Create(new EventSubscriberHostArgs(TestSetUp.CreateLogger(), ts)).ReceiveAsync(ed);

            Assert.IsTrue(ts.MessageReceived);
            Assert.AreEqual("TestUser", ts.Username);
            Assert.AreEqual("TEST", ts.Value);
            Assert.AreEqual(typeof(string), ts.ValueType);
        }
コード例 #28
0
        public void OneTimeSetUp()
        {
            var config = AgentTester.BuildConfiguration <Startup>("Beef");

            TestSetUp.SetDefaultLocalReferenceData <IReferenceData, ReferenceDataAgentProvider, IReferenceDataAgent, ReferenceDataAgent>();
            TestSetUp.RegisterSetUp(async(count, data) =>
            {
                return(await DatabaseExecutor.RunAsync(
                           count == 0 ? DatabaseExecutorCommand.ResetAndDatabase : DatabaseExecutorCommand.ResetAndData,
                           config["ConnectionStrings:BeefDemo"], useBeefDbo: true,
                           typeof(Database.Program).Assembly, Assembly.GetExecutingAssembly(), typeof(Beef.Demo.Abc.Database.Scripts).Assembly).ConfigureAwait(false) == 0);
            });
        }
コード例 #29
0
ファイル: TesterBase.cs プロジェクト: Avanade/Beef
        /// <summary>
        /// Prepares the <see cref="ExecutionContext"/> using the specified <paramref name="username"/>, whilst also ensuring that the <see cref="LocalServiceProvider"/> scope is correctly configured.
        /// </summary>
        /// <param name="username">The username (<c>null</c> indicates to use the <see cref="TestSetUp.DefaultUsername"/>).</param>
        /// <param name="args">Optional argument that will be passed into the creation of the <see cref="ExecutionContext"/> (via the <see cref="TestSetUp.CreateExecutionContext"/> function).</param>
        /// <returns>The <see cref="AgentTesterWaf{TStartup}"/> instance to support fluent/chaining usage.</returns>
        /// <remarks>The <see cref="ExecutionContext"/> must be created by the <see cref="AgentTesterBase"/> as the <see cref="ExecutionContext.ServiceProvider"/> must be set to <see cref="LocalServiceProvider"/>.</remarks>
        public void PrepareExecutionContext(string?username, object?args = null)
        {
            ExecutionContext.Reset();
            var ec = TestSetUp.CreateExecutionContext(username ?? TestSetUp.DefaultUsername, args);

            ec.ServiceProvider = LocalServiceProvider;
            ec.Properties.Add(ServiceCollectionKey, _serviceCollection);
            if (string.IsNullOrEmpty(ec.CorrelationId))
            {
                ec.CorrelationId = Guid.NewGuid().ToString();
            }

            ExecutionContext.SetCurrent(ec);
        }
コード例 #30
0
ファイル: PersonTest.cs プロジェクト: keithlemon/Beef
 public void A130_Validation_Invalid()
 {
     TestSetUp.CreateMock <IPersonData>();
     ExpectValidationException.Run(
         () => (new PersonManager()).CreateAsync(new Person()
     {
         FirstName = 'x'.ToLongString(), LastName = 'x'.ToLongString(), Birthday = DateTime.Now.AddDays(1), Gender = "X", EyeColor = "Y"
     }),
         "First Name must not exceed 50 characters in length.",
         "Last Name must not exceed 50 characters in length.",
         "Gender is invalid.",
         "Eye Color is invalid.",
         "Birthday must be less than or equal to Today.");
 }