Beispiel #1
0
        public async Task OneTimeSetUp()
        {
            TestSetUp.Reset(false);

            _robotTest = new RobotTest();
            await _robotTest.OneTimeSetUp();
        }
Beispiel #2
0
        /// <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);
        }
Beispiel #3
0
        /// <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);
        }
Beispiel #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[] { }));
        }
        public void OneTimeSetUp()
        {
            TestSetUp.Reset();

            AgentTester.Create <PersonAgent, Person>()
            .ExpectStatusCode(HttpStatusCode.NotFound)
            .Run((a) => a.Agent.GetAsync(404.ToGuid()));
        }
Beispiel #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()));
        }
 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"
     });
 }
Beispiel #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";
        }
Beispiel #9
0
        /// <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}");
                }
            }
        }
        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());
        }
Beispiel #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));
        }
        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);
        }
Beispiel #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"
            });
        }
        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);
        }
Beispiel #15
0
 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();
 }
Beispiel #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);
        }
        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);
        }
Beispiel #18
0
        /// <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);
            }
        }
        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);
        }
Beispiel #20
0
        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.");
        }
Beispiel #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_");
        }
Beispiel #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_");
        }
Beispiel #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);
        }
Beispiel #24
0
        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");
        }
        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);
        }
Beispiel #26
0
        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;
        }
Beispiel #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);
        }
Beispiel #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);
            });
        }
Beispiel #29
0
        /// <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);
        }
Beispiel #30
0
 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.");
 }