True() public static method

Verifies that an expression is true.
Thrown when the condition is false
public static True ( bool condition ) : void
condition bool The condition to be inspected
return void
コード例 #1
0
        public void GraphDTOFieldsTest()
        {
            GraphDTO dto = Misc.CreateGraphDTO();

            Assert.True(dto.VertexMap.Count == 4);
            Assert.True(dto.VertexMap[0] == dto.Vertex(Misc.g1));
            Assert.True(dto.VertexMap[1] == dto.Vertex(Misc.g2));
            Assert.True(dto.VertexMap[2] == dto.Vertex(Misc.g3));
            Assert.True(dto.VertexMap[3] == dto.Vertex(Misc.g4));

            Assert.True(dto.VertexMap[0] == dto.Vertex(0));
            Assert.True(dto.VertexMap[1] == dto.Vertex(1));
            Assert.True(dto.VertexMap[2] == dto.Vertex(2));
            Assert.True(dto.VertexMap[3] == dto.Vertex(3));

            {
                VertexDTO[] successors = dto.Successors(dto.Vertex(0)).ToArray();
                Assert.True(successors.Length == 2);
                Assert.Contains(dto.Vertex(1), successors);
                Assert.Contains(dto.Vertex(2), successors);
            }
            {
                VertexDTO[] successors = dto.Successors(dto.Vertex(1)).ToArray();
                Assert.True(successors.Length == 1);
                Assert.Contains(dto.Vertex(3), successors);
            }
            {
                VertexDTO[] successors = dto.Successors(dto.Vertex(2)).ToArray();
                Assert.True(successors.Length == 0);
            }
        }
コード例 #2
0
ファイル: RandomTest.cs プロジェクト: shyamalschandra/infer-1
        public void RandNormal()
        {
            double sum = 0, sum2 = 0;

            for (int i = 0; i < nsamples; i++)
            {
                double x = Rand.Normal();
                sum  += x;
                sum2 += x * x;
            }
            double m = sum / nsamples;
            double v = sum2 / nsamples - m * m;
            // the sample mean has stddev = 1/sqrt(n)
            double dError = System.Math.Abs(m);

            if (dError > 4 / System.Math.Sqrt(nsamples))
            {
                Assert.True(false, string.Format("m: error = {0}", dError));
            }

            // the sample variance is Gamma(n/2,n/2) whose stddev = sqrt(2/n)
            dError = System.Math.Abs(v - 1.0);
            if (dError > 4 * System.Math.Sqrt(2.0 / nsamples))
            {
                Assert.True(false, string.Format("v: error = {0}", dError));
            }
        }
コード例 #3
0
        public void IndexOfMaximumTest()
        {
            var    y = new Discrete(0.1, 0.4, 0.5);
            double expEv, gateEv, facEv;

            Console.WriteLine("explicit");
            var exp = IndexOfMaximumExplicit(y, out expEv);

            Console.WriteLine("gate");
            var gate = IndexOfMaximumFactorGate(y, out gateEv);

            Console.WriteLine("compiled alg");
            var facCA = IndexOfMaximumFactorCA(y, out facEv);

            Console.WriteLine("engine");
            var facIE = IndexOfMaximumFactorIE(y, out facEv);

            for (int i = 0; i < y.Dimension; i++)
            {
                Console.WriteLine("exp: " + exp[i] + " facCA: " + facCA[i] + " fac: " + facIE[i] + " gate: " + gate[i]);
                Assert.True(exp[i].MaxDiff(facCA[i]) < 1e-8);
                Assert.True(exp[i].MaxDiff(gate[i]) < 1e-8);
                Assert.True(exp[i].MaxDiff(facIE[i]) < 1e-8);
            }
            Assert.True(MMath.AbsDiff(expEv, facEv) < 1e-8);
            Assert.True(MMath.AbsDiff(expEv, gateEv) < 1e-8);
        }
コード例 #4
0
ファイル: RandomTest.cs プロジェクト: shyamalschandra/infer-1
        private void RandNormalBetween(double lowerBound, double upperBound)
        {
            double meanExpected, varianceExpected;

            new Microsoft.ML.Probabilistic.Distributions.TruncatedGaussian(0, 1, lowerBound, upperBound).GetMeanAndVariance(out meanExpected, out varianceExpected);

            MeanVarianceAccumulator mva = new MeanVarianceAccumulator();

            for (int i = 0; i < nsamples; i++)
            {
                double x = Rand.NormalBetween(lowerBound, upperBound);
                mva.Add(x);
            }
            double m = mva.Mean;
            double v = mva.Variance;

            Console.WriteLine("mean = {0} should be {1}", m, meanExpected);
            Console.WriteLine("variance = {0} should be {1}", v, varianceExpected);
            // the sample mean has stddev = 1/sqrt(n)
            double dError = System.Math.Abs(m - meanExpected);

            if (dError > 4 / System.Math.Sqrt(nsamples))
            {
                Assert.True(false, string.Format("m: error = {0}", dError));
            }

            // the sample variance is Gamma(n/2,n/2) whose stddev = sqrt(2/n)
            dError = System.Math.Abs(v - varianceExpected);
            if (dError > 4 * System.Math.Sqrt(2.0 / nsamples))
            {
                Assert.True(false, string.Format("v: error = {0}", dError));
            }
        }
コード例 #5
0
ファイル: RandomTest.cs プロジェクト: shyamalschandra/infer-1
        private void RandBinomial(double p, int n)
        {
            double meanExpected     = p * n;
            double varianceExpected = p * (1 - p) * n;
            double sum  = 0;
            double sum2 = 0;

            for (int i = 0; i < nsamples; i++)
            {
                double x = Rand.Binomial(n, p);
                sum  += x;
                sum2 += x * x;
            }
            double mean     = sum / nsamples;
            double variance = sum2 / nsamples - mean * mean;
            double error    = MMath.AbsDiff(meanExpected, mean, 1e-6);

            if (error > System.Math.Sqrt(varianceExpected) * 5)
            {
                Assert.True(false, string.Format("Binomial({0},{1}) mean = {2} should be {3}, error = {4}", p, n, mean, meanExpected, error));
            }
            error = MMath.AbsDiff(varianceExpected, variance, 1e-6);
            if (error > System.Math.Sqrt(varianceExpected) * 5)
            {
                Assert.True(false, string.Format("Binomial({0},{1}) variance = {2} should be {3}, error = {4}", p, n, variance, varianceExpected, error));
            }
        }
コード例 #6
0
        public void TestComponentLoadFailureWithPreviousErrorWriter()
        {
            IntPtr previousWriter = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(
                (HostPolicyMock.ErrorWriterDelegate)((string _) => { Assert.True(false, "Should never get here"); }));

            using (HostPolicyMock.MockValues_corehost_set_error_writer errorWriterMock =
                       HostPolicyMock.Mock_corehost_set_error_writer(previousWriter))
            {
                using (HostPolicyMock.MockValues_corehost_resolve_component_dependencies resolverMock =
                           HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                               134,
                               "",
                               "",
                               ""))
                {
                    Assert.Throws <InvalidOperationException>(() =>
                    {
                        AssemblyDependencyResolver resolver = new AssemblyDependencyResolver(
                            Path.Combine(TestBasePath, _componentAssemblyPath));
                    });

                    // After everything is done, the error writer should be reset to the original value.
                    Assert.Equal(previousWriter, errorWriterMock.LastSetErrorWriterPtr);
                }
            }
        }
コード例 #7
0
        public void GammaCustomSerializationTest()
        {
            using (var stream = new MemoryStream())
            {
                var writer = new WrappedBinaryWriter(new BinaryWriter(stream));
                writer.Write(Gamma.FromShapeAndRate(1.0, 10.0));
                writer.Write(Gamma.PointMass(Math.PI));
                writer.Write(Gamma.Uniform());

                stream.Seek(0, SeekOrigin.Begin);

                using (var reader = new WrappedBinaryReader(new BinaryReader(stream)))
                {
                    Gamma shapeAndRate = reader.ReadGamma();
                    Assert.Equal(1.0, shapeAndRate.Shape);
                    Assert.Equal(10.0, shapeAndRate.Rate);

                    Gamma pointMass = reader.ReadGamma();
                    Assert.True(pointMass.IsPointMass);
                    Assert.Equal(Math.PI, pointMass.GetMean());

                    Gamma uniform = reader.ReadGamma();
                    Assert.True(uniform.IsUniform());
                }
            }
        }
コード例 #8
0
        private async Task RunTypesTest(string path, Version version, bool inProcess, TargetPlatform target)
        {
            // init engine
            var engine = EngineProvider.Get(version, path, null, inProcess, target, true);
            await engine.Initialize(null, _ct);

            // load test script
            var pyScript = await engine.LoadScript(_typeTestScript, _ct);

            foreach (var typeInfo in _types)
            {
                var    element = typeInfo.Value;
                object array   = Array.CreateInstance(typeInfo.Key, 10);

                // invoke with simple type
                var resObj = await engine.InvokeMethod(pyScript, "dummy", new[] { element }, _ct);

                var simpleType = engine.Convert(resObj, typeInfo.Key);
                Assert.True(typeInfo.Key == simpleType.GetType());

                // invoke with array type
                resObj = await engine.InvokeMethod(pyScript, "dummy", new[] { array }, _ct);

                var arrayType = engine.Convert(resObj, array.GetType());
                Assert.True(array.GetType() == arrayType.GetType());
            }
            await engine.Release();
        }
コード例 #9
0
        public void HttpAuthorizeAttribute_OnAuthorize_WithAuthorizedHeader_ReturnsAuthorization()
        {
            ConfigUtilityMock.Setup(x => x.ApiKey).Returns(ApiKey);

            var po     = new PrivateObject(ClassUnderTest);
            var scheme = (string)po.GetField("Scheme", BindingFlags.NonPublic | BindingFlags.Static);

            var headerValue       = new AuthenticationHeaderValue(scheme, ApiKey);
            var context           = new HttpActionContext();
            var request           = new HttpRequestMessage();
            var controllerContext = new HttpControllerContext();

            request.Headers.Authorization = headerValue;
            controllerContext.Request     = request;
            context.ControllerContext     = controllerContext;
            context.Request.RequestUri    = new Uri("http://test.com");

            var isAuthorizedWasCalled = false;
            var expectedContext       = new HttpActionContext();

            ShimAuthorizeAttribute.AllInstances.IsAuthorizedHttpActionContext = (x, y) =>
            {
                isAuthorizedWasCalled = true;
                expectedContext       = y;

                return(true);
            };

            ClassUnderTest.OnAuthorization(context);

            Assert.Null(context.Response);
            Assert.True(isAuthorizedWasCalled);
            Assert.Equal(expectedContext, context);
        }
コード例 #10
0
        public void GetCpuUsage_WhenExtensionPointProcessWriteError_ShouldDisposeAndSetDataToNegative()
        {
            var    tempFileName = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ps1"));
            string exec;
            string args;
            var    jsonCpuUsage = "{\"MachineCpuUsage\":57, \"ProcessCpuUsage\":2.5}";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                exec         = "PowerShell";
                jsonCpuUsage = $"\"{jsonCpuUsage.Replace("\"", "`\"")}\"";
                const string error = "\"Big error!\"";

                var pshScript = string.Format(@"
while($TRUE){{
	Write-Host {0}
    Write-Error {1}
	Start-Sleep 1
}}", jsonCpuUsage, error);

                args = "-NoProfile " + tempFileName;
                File.WriteAllText(tempFileName, pshScript);
            }
            else
            {
                var bashScript = "#!/bin/bash \nfor i in {1..100} \ndo \n 	echo "+ jsonCpuUsage.Replace("\"", "\\\"") + "\n __________ \n	sleep 1 \ndone";

                exec = "bash";
                args = tempFileName;
                File.WriteAllText(tempFileName, bashScript);
                Process.Start("chmod", $"755 {tempFileName}");
            }

            using (var extensionPoint = new CpuUsageExtensionPoint(
                       new JsonContextPool(),
                       exec,
                       args,
                       Server.ServerStore.NotificationCenter))
            {
                extensionPoint.Start();

                var startTime = DateTime.Now;
                var value     = new ExtensionPointData {
                    ProcessCpuUsage = 0, MachineCpuUsage = 0
                };
                while (Math.Abs(value.MachineCpuUsage) < 0.1 || Math.Abs(57 - value.MachineCpuUsage) < 0.1)
                {
                    if ((DateTime.Now - startTime).Seconds > 10)
                    {
                        throw new TimeoutException();
                    }
                    value = extensionPoint.Data;
                }

                Assert.True(value.MachineCpuUsage < 0, $"Got {value} {nameof(value.MachineCpuUsage)} should get negative error value");
                Assert.True(value.ProcessCpuUsage < 0, $"Got {value} {nameof(value.ProcessCpuUsage)} should get negative error value");

                Assert.True(extensionPoint.IsDisposed, "Should dispose the extension point object if the process exited");
            }
        }
コード例 #11
0
        public void ShouldEnabledSaveCommandWhenFriendChanged()
        {
            _friendEditViewModelMoq.Load(FriendId);
            _friendEditViewModelMoq.Friend.FirstName = "Julia";

            Assert.True(_friendEditViewModelMoq.SaveCommand.CanExecute(null));
        }
コード例 #12
0
        public void ParallelSchedulerTest2()
        {
            ParallelScheduler ps = new ParallelScheduler();

            ps.FillIdleSlots = true;
            int depth = 10;

            int[][] variablesUsedByNode = Util.ArrayInit(2 * depth + 1, i =>
            {
                if (i < depth)
                {
                    return(new int[] { 0 });
                }
                else if (i < 2 * depth)
                {
                    return(new int[] { i - depth });
                }
                else
                {
                    return(Util.ArrayInit(depth, j => j));
                }
            });
            ps.CreateGraph(variablesUsedByNode);
            var schedule = ps.GetScheduleWithBarriers(2);

            ParallelScheduler.WriteSchedule(schedule);
            var perThread = ps.ConvertToSchedulePerThread(schedule, 2);

            Assert.True(perThread[1][0].Length == 0);
            Assert.True(perThread[0][2].Length == 0);
        }
コード例 #13
0
        public async void ConfirmSpotBooked_ExpectedTrue_Success()
        {
            using (var context = Fixture.CreateContext())
            {
                // arrange
                bool spotsCreated = await GenerateBookingData.CreateBookingWithOneSpot() != null;

                bool                  expected           = true;
                ILocationService      locationService    = new LocationService(context);
                IMarinaService        marinaService      = new MarinaService(context, locationService);
                IBookingFormService   bookingFormService = new BookingFormService(context, marinaService);
                IBookingLineService   service            = new BookingLineService(context, bookingFormService);
                IPDFService <Booking> pDFService         = new BookingPDFService();
                IBookingService       bookingService     = new BookingService(context, service, null, pDFService, null);
                IMarinaOwnerService   marinaOwnerService = new MarinaOwnerService(context, service);

                // act
                var unconfirmedBookingLines = (List <BookingLine>) await marinaOwnerService.GetUnconfirmedBookingLines(1);

                bool actual = await bookingService.ConfirmSpotBooked(unconfirmedBookingLines.First().BookingLineId);

                // assert
                Assert.True(spotsCreated);
                Assert.Equal(expected, actual);
            }
        }
コード例 #14
0
        public void SendThenErrorDoesRetry()
        {
            var cts = new CancellationTokenSource(10000);

            var      obj            = FakeData.New();
            FakeData receivedObject = null;

            bool didThrowOnce = false;

            processor.PushToQueue(obj);

            processor.Received += o =>
            {
                if (o.TotalRetries == 0)
                {
                    didThrowOnce = true;
                    throw new Exception();
                }

                receivedObject = o;
                cts.Cancel();
            };

            processor.Run(cts.Token);

            Assert.True(didThrowOnce);
            Assert.Equal(obj, receivedObject);
        }
コード例 #15
0
        public void ConceptChronologyDTOCompareToTest()
        {
            {
                ConceptChronologyDTO a = Misc.CreateConceptChronologyDTO;
                ConceptChronologyDTO b = Misc.CreateConceptChronologyDTO;
                Assert.True(a.CompareTo(b) == 0);
            }

            {
                ConceptChronologyDTO a = Misc.CreateConceptChronologyDTO;
                ConceptChronologyDTO b = Misc.CreateConceptChronologyDTO
                                         with
                {
                    PublicId = new PublicId(Misc.g2, Misc.g2, Misc.g3, Misc.g4)
                };
                Assert.False(a.CompareTo(b) == 0);
            }

            {
                ConceptChronologyDTO a = new ConceptChronologyDTO(
                    Misc.PublicIdG,
                    Misc.ConceptVersionsBase(Misc.PublicIdG).ToImmutableArray()
                    );
                ConceptChronologyDTO b = new ConceptChronologyDTO(
                    Misc.PublicIdG,
                    new ConceptVersionDTO[]
                {
                    Misc.cv1(Misc.PublicIdG)
                }.ToImmutableArray()
                    );
                Assert.False(a.CompareTo(b) == 0);
            }
        }
コード例 #16
0
        public void DiGraphDTOFieldsTest()
        {
            DiGraphDTO dto = Misc.CreateDiGraphDTO();

            Assert.True(dto.VertexMap.Count == 4);
            Assert.True(dto.VertexMap[0] == dto.Vertex(Misc.g1));
            Assert.True(dto.VertexMap[1] == dto.Vertex(Misc.g2));
            Assert.True(dto.VertexMap[2] == dto.Vertex(Misc.g3));
            Assert.True(dto.VertexMap[3] == dto.Vertex(Misc.g4));

            Assert.True(dto.VertexMap[0] == dto.Vertex(0));
            Assert.True(dto.VertexMap[1] == dto.Vertex(1));
            Assert.True(dto.VertexMap[2] == dto.Vertex(2));
            Assert.True(dto.VertexMap[3] == dto.Vertex(3));

            Assert.True(dto.Predecessors(dto.Vertex(1)).Count() == 1);
            Assert.True(dto.Predecessors(dto.Vertex(1)).ElementAt(0) == dto.Vertex(0));

            Assert.True(dto.Predecessors(dto.Vertex(2)).Count() == 1);
            Assert.True(dto.Predecessors(dto.Vertex(2)).ElementAt(0) == dto.Vertex(0));

            Assert.True(dto.Predecessors(dto.Vertex(3)).Count() == 2);
            Assert.Contains(dto.Vertex(1), dto.Predecessors(dto.Vertex(3)));
            Assert.Contains(dto.Vertex(2), dto.Predecessors(dto.Vertex(3)));
        }
コード例 #17
0
        public void TestAssembly()
        {
            string assemblyDependencyPath = CreateMockAssembly("AssemblyDependency.dll");

            IntPtr previousWriter = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(
                (HostPolicyMock.ErrorWriterDelegate)((string _) => { Assert.True(false, "Should never get here"); }));

            using (HostPolicyMock.MockValues_corehost_set_error_writer errorWriterMock =
                       HostPolicyMock.Mock_corehost_set_error_writer(previousWriter))
            {
                using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                           0,
                           assemblyDependencyPath,
                           "",
                           ""))
                {
                    AssemblyDependencyResolver resolver = new AssemblyDependencyResolver(
                        Path.Combine(TestBasePath, _componentAssemblyPath));

                    Assert.Equal(
                        assemblyDependencyPath,
                        resolver.ResolveAssemblyToPath(new AssemblyName("AssemblyDependency")));

                    // After everything is done, the error writer should be reset to the original value.
                    Assert.Equal(previousWriter, errorWriterMock.LastSetErrorWriterPtr);
                }
            }
        }
コード例 #18
0
ファイル: FieldCompareTests.cs プロジェクト: HL7/tinkar-cs
        public void FieldCompareMapTest()
        {
            {
                ImmutableDictionary <Int32, String> aDict = ImmutableDictionary <int, string> .Empty;
                aDict = aDict.Add(1, "abc");
                aDict = aDict.Add(2, "def");
                Assert.True(FieldCompare.CompareMap <Int32, String>(aDict, aDict) == 0);
            }

            {
                ImmutableDictionary <Int32, String> aDict = ImmutableDictionary <int, string> .Empty;
                aDict = aDict.Add(1, "abc");
                aDict = aDict.Add(2, "def");

                ImmutableDictionary <Int32, String> bDict = ImmutableDictionary <int, string> .Empty;
                bDict = bDict.Add(1, "abc");
                Assert.True(FieldCompare.CompareMap <Int32, String>(aDict, bDict) > 0);
                Assert.True(FieldCompare.CompareMap <Int32, String>(bDict, aDict) < 0);
            }

            {
                ImmutableDictionary <Int32, String> aDict = ImmutableDictionary <int, string> .Empty;
                aDict = aDict.Add(1, "abc");
                aDict = aDict.Add(2, "def");

                ImmutableDictionary <Int32, String> bDict = ImmutableDictionary <int, string> .Empty;
                bDict = bDict.Add(2, "abc");
                bDict = bDict.Add(1, "def");
                Assert.True(FieldCompare.CompareMap <Int32, String>(aDict, bDict) < 0);
                Assert.True(FieldCompare.CompareMap <Int32, String>(bDict, aDict) > 0);
            }
        }
コード例 #19
0
        public void GaussianCustomSerializationTest()
        {
            using (var stream = new MemoryStream())
            {
                var writer = new WrappedBinaryWriter(new BinaryWriter(stream));
                writer.Write(Gaussian.FromNatural(-13.89, 436.12));
                writer.Write(Gaussian.PointMass(Math.PI));
                writer.Write(Gaussian.Uniform());

                stream.Seek(0, SeekOrigin.Begin);

                using (var reader = new WrappedBinaryReader(new BinaryReader(stream)))
                {
                    Gaussian natural = reader.ReadGaussian();
                    Assert.Equal(-13.89, natural.MeanTimesPrecision);
                    Assert.Equal(436.12, natural.Precision);

                    Gaussian pointMass = reader.ReadGaussian();
                    Assert.True(pointMass.IsPointMass);
                    Assert.Equal(Math.PI, pointMass.GetMean());

                    Gaussian uniform = reader.ReadGaussian();
                    Assert.True(uniform.IsUniform());
                }
            }
        }
コード例 #20
0
        public void Equality_IsEqual()
        {
            var a = new float3x3(1, 1, 1, 1, 1, 1, 1, 1, 1);
            var b = new float3x3(1, 1, 1, 1, 1, 1, 1, 1, 1);

            Assert.True((a == b));
        }
コード例 #21
0
        public void Add_WithTheSameLocation_ReturnUnsuccessful(
            FriendService sut,
            Friend newFriend)
        {
            var myFriendsCollection = Builder <Friend> .CreateListOfSize(10).All()
                                      .TheFirst(1)
                                      .With(x => x.Name     = "Sergio")
                                      .With(x => x.Location = new Location
            {
                Latitude = 10, Longitude = 10
            })
                                      .Build()
                                      .ToList();

            sut.InMemoryCacheService.Remove(CacheKey);
            sut.InMemoryCacheService.Insert(CacheKey, myFriendsCollection);

            newFriend.Location.Latitude  = 10;
            newFriend.Location.Longitude = 10;

            var result = sut.Add(newFriend);

            Assert.False(result.Succeeded);
            Assert.True(result.Reason == ServiceResultFailReason.BusinessValidation);
            Assert.Contains("Já existe um amigo nessa mesma localização.", result.Errors);
        }
コード例 #22
0
        public void Inequality_IsInequal()
        {
            var a = new float3x3(1, 1, 1, 1, 1, 1, 1, 1, 1);
            var b = new float3x3(0, 0, 0, 0, 0, 0, 0, 0, 0);

            Assert.True((a != b));
        }
コード例 #23
0
ファイル: RandomTest.cs プロジェクト: shyamalschandra/infer-1
        private void RandGamma(double a)
        {
            double sum  = 0;
            double sum2 = 0;

            for (int i = 0; i < nsamples; i++)
            {
                double x = Rand.Gamma(a);
                sum  += x;
                sum2 += x * x;
            }
            double m = sum / nsamples;
            double v = sum2 / nsamples - m * m;

            Console.WriteLine("Gamma({2}) mean: {0} variance: {1}", m, v, a);

            // sample mean has stddev = sqrt(a/n)
            double dError = System.Math.Abs(m - a);

            if (dError > 4 * System.Math.Sqrt(a / nsamples))
            {
                Assert.True(false, string.Format("m: error = {0}", dError));
            }

            dError = System.Math.Abs(v - a);
            if (dError > TOLERANCE)
            {
                Assert.True(false, String.Format("v: error = {0}", dError));
            }
        }
コード例 #24
0
ファイル: TypeInference.cs プロジェクト: JOE-DEK-IT/dotnet
        private static void TestInferGenericParameters(MethodInfo method, Type[] args, int minTrueCount)
        {
            Console.WriteLine("Inferring {0} from {1}:", method, Invoker.PrintTypes(args));
            IList <Exception>     lastError = new List <Exception>();
            IEnumerator <Binding> iter      = Binding.InferGenericParameters(method, args, ConversionOptions.AllConversions, lastError);
            int count = 0;

            while (iter.MoveNext())
            {
                Console.WriteLine(iter.Current);
                count++;
            }
            if (count < minTrueCount)
            {
                if (lastError.Count > 0)
                {
                    throw lastError[0];
                }
                else
                {
                    throw new Exception(String.Format("Only got {0} matches instead of {1}", count, minTrueCount));
                }
            }
            if (minTrueCount >= 0)
            {
                Assert.True(count >= minTrueCount);                    // count may be greater on newer runtimes
            }
            if (minTrueCount == 0)
            {
                Console.WriteLine("Correctly failed with exceptions: ");
                Console.WriteLine(StringUtil.ToString(lastError));
            }
        }
コード例 #25
0
ファイル: RandomTest.cs プロジェクト: shyamalschandra/infer-1
        private void RandMultinomial(DenseVector p, int n)
        {
            Vector      meanExpected     = p * n;
            Vector      varianceExpected = p * (1 - p) * n;
            DenseVector sum  = DenseVector.Zero(p.Count);
            DenseVector sum2 = DenseVector.Zero(p.Count);

            for (int i = 0; i < nsamples; i++)
            {
                int[] x = Rand.Multinomial(n, p);
                for (int dim = 0; dim < x.Length; dim++)
                {
                    sum[dim]  += x[dim];
                    sum2[dim] += x[dim] * x[dim];
                }
            }
            Vector mean     = sum * (1.0 / nsamples);
            Vector variance = sum2 * (1.0 / nsamples) - mean * mean;

            for (int dim = 0; dim < p.Count; dim++)
            {
                double error = MMath.AbsDiff(meanExpected[dim], mean[dim], 1e-6);
                Console.WriteLine("Multinomial({0},{1})     mean[{5}] = {2} should be {3}, error = {4}", p, n, mean[dim], meanExpected[dim], error, dim);
                Assert.True(error < TOLERANCE);
                error = MMath.AbsDiff(varianceExpected[dim], variance[dim], 1e-6);
                Console.WriteLine("Multinomial({0},{1}) variance[{5}] = {2} should be {3}, error = {4}", p, n, variance[dim], varianceExpected[dim], error, dim);
                Assert.True(error < TOLERANCE);
            }
        }
コード例 #26
0
        public void ShouldAddProductToCart()
        {
            var mockDB = new Mock <ICart>();

            mockDB.Setup(c => c.ToCart(GetProduct(), GetCart(), 1))
            .Returns(true);

            var mockProductService = new Mock <IProductService>();

            mockProductService.Setup(p => p.FindById(new ProductFindRequest
            {
                ProductId = 2
            })).Returns(new ProductFindResponse
            {
                FoundProduct = GetProduct()
            });

            mockDB.Setup(c => c.ReadById(GetCartById()))
            .Returns(GetCart());

            _cartValidation = new CartValidation(_addProductToCartValidation, _cartCreateRequestValidation, _cartFindRequestValidation, _cartRemoveRequestValidation, _removeFromCartRequestValidation, _cartClearRequestValidation);

            _victim = new CartService(mockDB.Object, mockProductService.Object, _cartValidation);

            var actual = _victim.AddToCart(AddItemToCart()).HasAdded;

            Assert.True(actual);
        }
コード例 #27
0
        public void PatternChronologyDTOIsEquivalentTest()
        {
            {
                PatternChronologyDTO a = Misc.CreatePatternChronologyDTO;
                PatternChronologyDTO b = Misc.CreatePatternChronologyDTO;
                Assert.True(a.IsEquivalent(b));
            }

            {
                PatternChronologyDTO a = Misc.CreatePatternChronologyDTO;
                PatternChronologyDTO b = Misc.CreatePatternChronologyDTO
                                         with
                {
                    PublicId = new PublicId(Misc.other)
                };
                Assert.False(a.IsEquivalent(b));
            }

            {
                PatternChronologyDTO a = Misc.CreatePatternChronologyDTO;
                PatternChronologyDTO b = Misc.CreatePatternChronologyDTO
                                         with
                {
                    Versions = new PatternVersionDTO[]
                    {
                        Misc.CreatePatternVersionDTO
                        with
                        {
                            PublicId = new PublicId(Misc.other)
                        }
                    }.ToImmutableArray()
コード例 #28
0
        public void ConceptChronologyDTOIsEquivalentTest()
        {
            {
                ConceptChronologyDTO a = Misc.CreateConceptChronologyDTO;
                ConceptChronologyDTO b = Misc.CreateConceptChronologyDTO;
                Assert.True(a.IsEquivalent(b));
            }

            {
                ConceptChronologyDTO a = Misc.CreateConceptChronologyDTO;
                ConceptChronologyDTO b = Misc.CreateConceptChronologyDTO
                                         with
                {
                    PublicId = new PublicId(Misc.other)
                };
                Assert.False(a.IsEquivalent(b));
            }

            {
                ConceptChronologyDTO a = new ConceptChronologyDTO(
                    Misc.PublicIdG,
                    Misc.ConceptVersionsBase(Misc.PublicIdG).ToImmutableArray()
                    );
                ConceptChronologyDTO b = new ConceptChronologyDTO(
                    Misc.PublicIdG,
                    new ConceptVersionDTO[]
                {
                    Misc.cv1(Misc.PublicIdG)
                }.ToImmutableArray()
                    );
                Assert.False(a.IsEquivalent(b));
            }
        }
コード例 #29
0
        public void GetDateOfBirthTest()
        {
            DateTime expected = new DateTime(1988, 4, 16, 0, 0, 0);
            DateTime?result   = PersonalCodeUtils.GetDateOfBirth("38804161728");

            Assert.True(expected.Equals(result));
        }
コード例 #30
0
        public void MockServerProcessorStopBeforeStartTest()
        {
            var Target = this.mockServerProcessor;
            var Actual = Target.Stop();

            Assert.True(Actual);
        }