public async Task When_Json_Body_Then_Populates(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expected = new JsonOperation
            {
                IntegerProperty  = 761,
                EnumProperty     = OperationEnum.EnumOne,
                GuidProperty     = Guid.NewGuid(),
                StringArray      = new[] { "arr1", "arr2" },
                StringEnumerable = new[] { "arr3", "arr4" },
                StringList       = new List <string> {
                    "arr5", "arr6"
                },
                StringProperty          = "a string",
                NullableIntegerProperty = null,
                StringIntegerDictionary = new Dictionary <string, int> {
                    { "one", 1 }, { "twice", 12 }
                }
            };

            var handler  = new TestApiOperationHandler <JsonOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(
                o => o.WithHandler(handler),
                configureHttp: configureHttp);
            var context = GetContext(executor, expected);

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
        }
        /// <summary>
        /// Transfer a number of instances from the unlabelled to the labelled set for the given resident.
        /// </summary>
        /// <param name="resident">The index of the resident.</param>
        /// <param name="num">The number to transfer.</param>
        public void Transfer(int resident, int num)
        {
            if (num == 0)
            {
                return;
            }

            var rng = new Random();

            for (int tt = 0; tt < 2; ++tt)
            {
                for (int nn = 0; nn < num; ++nn)
                {
                    var uinds = Unlabelled.OrderBy(x => rng.Next());

                    foreach (var ind in uinds)
                    {
                        if (dataSet.Labels[0][ind] == (tt == 0 ? false : true))
                        {
                            Unlabelled.Remove(ind);
                            Labelled.Add(ind);
                            break;
                        }
                    }
                }
            }
        }
        public void VOITest(int numActivelySelected, Marginals priors)
        {
            var onlineEstimates = new List <Bernoulli>();
            var onlineTargets   = new List <bool>();

            Metrics metrics = null;

            for (int jj = 0; jj < numActivelySelected; ++jj)
            {
                CalculateProbabilities(priors);

                //Console.WriteLine( "\nJL: {0}", JL() );
                //Console.WriteLine( "JU: {0}", JU() );

                int    argMax;
                double maxVal;
                GetArgMaxVOI(hypothesisActivityPosteriors, priors, out argMax, out maxVal);

                Unlabelled.Remove(argMax);
                Labelled.Add(argMax);

                UpdateModel(argMax);


                onlineEstimates.Add(GetProbabilityOf(argMax, priors));
                onlineTargets.Add(DataSet.Labels[0][argMax]);

                metrics = new Metrics
                {
                    Name       = "active",
                    Estimates  = onlineEstimates.Select(ia => new Bernoulli(ia)).ToArray(),
                    TrueLabels = onlineTargets.ToArray()
                };

                // metrics.PrintSummary();
            }

            if (Unlabelled.Any())
            {
                CalculateProbabilities(priors);
                foreach (var index in Unlabelled)
                {
                    onlineEstimates.Add(hypothesisActivityPosteriors[index]);
                    onlineTargets.Add(DataSet.Labels[0][index]);
                }

                metrics = new Metrics
                {
                    Name       = "active",
                    Estimates  = onlineEstimates.Select(ia => new Bernoulli(ia)).ToArray(),
                    TrueLabels = onlineTargets.ToArray()
                };
            }

            if (metrics != null)
            {
                metrics.PrintSummary();
            }
        }
        /// <summary>
        /// Updates the model.
        /// </summary>
        /// <param name="index">Index.</param>
        public void UpdateModel(int index)
        {
            if (Labelled.Contains(index))
            {
                throw new Exception("The selected index is already in the labelled set.");
            }

            Unlabelled.Remove(index);
            Labelled.Add(index);
        }
        public async Task When_Malformed_JSON_Then_Throws_ApiException(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var handler  = new TestApiOperationHandler <JsonOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);

            var context = executor.HttpContextFor <JsonOperation>();

            context.GetHttpContext().Request.Body = "{..}".AsUtf8Stream();
            context.GetHttpContext().Request.Headers["Content-Type"] = "application/json";

            // Act
            Func <Task> tryExecute = () => executor.ExecuteAsync(context);

            // Assert
            await tryExecute.Should()
            .ThrowApiExceptionAsync()
            .WithType("invalid_json")
            .WithTitle("The JSON payload is invalid");
        }
        public async Task When_Json_Body_And_FromBody_Attribute_Then_Populates(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expectedBody = new JsonOperation
            {
                IntegerProperty  = 761,
                EnumProperty     = OperationEnum.EnumOne,
                GuidProperty     = Guid.NewGuid(),
                StringArray      = new[] { "arr1", "arr2" },
                StringEnumerable = new[] { "arr3", "arr4" },
                StringList       = new List <string> {
                    "arr5", "arr6"
                },
                StringProperty          = "a string",
                NullableIntegerProperty = null,
                StringIntegerDictionary = new Dictionary <string, int> {
                    { "one", 1 }, { "twice", 12 }
                }
            };

            var handler  = new TestApiOperationHandler <JsonOperationUsingFromBody>(null);
            var executor = TestApiOperationExecutor.CreateHttp(
                o => o.WithHandler(handler),
                configureHttp: configureHttp);

            var jsonBody = JsonConvert.SerializeObject(expectedBody);

            var context = executor.HttpContextFor <JsonOperationUsingFromBody>();

            context.GetHttpContext().Request.Body = jsonBody.AsUtf8Stream();
            context.GetHttpContext().Request.Headers["Content-Type"] = "application/json";

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(new JsonOperationUsingFromBody
            {
                JsonOperation = expectedBody,
            });
        }
        public async Task When_Route_Property_In_Json_Body_Then_Route_Value_Wins(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expected = new JsonWithRouteOperation
            {
                RouteProperty    = "unexpectedRouteValue",
                IntegerProperty  = 761,
                EnumProperty     = OperationEnum.EnumOne,
                GuidProperty     = Guid.NewGuid(),
                StringArray      = new[] { "arr1", "arr2" },
                StringEnumerable = new[] { "arr3", "arr4" },
                StringList       = new List <string> {
                    "arr5", "arr6"
                },
                StringProperty          = "a string",
                NullableIntegerProperty = null,
                StringIntegerDictionary = new Dictionary <string, int> {
                    { "one", 1 }, { "twice", 12 }
                }
            };

            var expectedRouteValue = "theRouteValue";

            var handler  = new TestApiOperationHandler <JsonWithRouteOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);
            var context  = GetContext(executor, expected);

            context.GetRouteData().Values[nameof(JsonWithRouteOperation.RouteProperty)] = expectedRouteValue;

            // Act
            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(
                expected,
                o => o.Excluding(x => x.RouteProperty));

            handler.OperationPassed.RouteProperty.Should().Be(expectedRouteValue);
        }
Exemple #8
0
 private Labelled <T> LoadLabelledWithFallback <T>(string folder, string name, string extension, Loader <T> loader, Labelled <T> fallback)
 {
     if (name == null)
     {
         return(fallback);
     }
     else
     {
         string path   = Path.Combine(folder, name + extension);
         T      loaded = loader(path);
         if (loaded == null)
         {
             return(fallback);
         }
         else
         {
             return(new Labelled <T> {
                 label = path, value = loaded
             });
         }
     }
 }
        public async Task When_Route_Property_In_Json_Body_But_Not_RouteData_With_Multiple_Routes_Then_Sets(Labelled <Action <BlueprintHttpBuilder> > configureHttp)
        {
            // Arrange
            var expected = new MultipleRouteOperation {
                RouteProperty = "expectedValue"
            };

            var handler  = new TestApiOperationHandler <MultipleRouteOperation>(null);
            var executor = TestApiOperationExecutor.CreateHttp(o => o.WithHandler(handler), configureHttp: configureHttp);
            var context  = GetContext(executor, expected);

            // Act
            var source = executor.WhatCodeDidIGenerate();

            await executor.ExecuteAsync(context);

            // Assert
            handler.OperationPassed.Should().BeEquivalentTo(expected);
            handler.OperationPassed.RouteProperty.Should().Be(expected.RouteProperty);
        }