Exemplo n.º 1
0
        public void CalculatorDoubleTest(string expression, double expected)
        {
            var calculator = new CalculatorService();
            var result     = calculator.CalculateExpression(expression);

            Assert.Equal(expected, result);
        }
Exemplo n.º 2
0
        public void TestAllPlus()
        {
            var expression = "10+100+1000+10000";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(11110, actual.Value, 0, "TestAllPlus passed");
        }
Exemplo n.º 3
0
        public void TaskTest3()
        {
            var expression = "4+5/2-1";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(5.5, actual.Value, 0.0001, "TaskTest3 passed");
        }
Exemplo n.º 4
0
        public void TestMix3()
        {
            var expression = "-45-20*5*12+34/13";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(-1242.38461538, actual.Value, 0.0001, "TestMix3 passed");
        }
Exemplo n.º 5
0
        public void TaskTest1()
        {
            var expression = "4+5*2";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(14, actual.Value, 0.0001, "TaskTest1 passed");
        }
Exemplo n.º 6
0
        public void Calculate_FailsValidation_ReturnsExpectedResult()
        {
            // Arrange
            var calculatorService = new CalculatorService(_logger.Object);
            var calculation       = new Mock <ICalculation <decimal> >(MockBehavior.Strict);

            var validationResult = new ValidationResult
            {
                IsValid = false,
                Errors  = new List <Error>
                {
                    new Error
                    {
                        ErrorCode = ErrorCode.InvalidParameters
                    }
                }
            };

            calculation.Setup(x => x.Validate()).Returns(validationResult);

            // Act
            var result = calculatorService.Calculate(calculation.Object);

            // Assert
            var expected = new CalculationResult <decimal> {
                Validation = validationResult
            };

            result.Should().BeEquivalentTo(expected);
            calculation.Verify(x => x.Validate(), Times.Once);
            _logger.VerifyNoOtherCalls();
        }
Exemplo n.º 7
0
        public void TestMix1()
        {
            var expression = "10 / 2 * 3 + 4 + 5 - 80";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(-56, actual.Value, 0.0001, "TestMix1 passed");
        }
Exemplo n.º 8
0
        public void TestAllMultiply()
        {
            var expression = "10* 100 * 1000";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(1000000, actual.Value, 0, "TestAllMultiply passed");
        }
Exemplo n.º 9
0
        public void TestAllDivide()
        {
            var expression = "10/ 100 / 1000";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(0.0001, actual.Value, 0.0001, "TestAllDivide passed");
        }
        public void CheckNumberInDivide_1_1_Should_Be_true()
        {
            var calculatorService = new CalculatorService();
            var actual            = calculatorService.CheckNumberInDivide(1, 1);

            Assert.IsTrue(actual);
        }
        public void CheckNumberInDivide_1_0_Should_Be_false()
        {
            var calculatorService = new CalculatorService();
            var actual            = calculatorService.CheckNumberInDivide(1, 0);

            Assert.IsFalse(actual);
        }
        public void Calculation_InvalidData_Error(CalculatorType type, decimal p1, decimal p2)
        {
            CalculatorService service = new CalculatorService(new MockCalculatorFactory(), new MockCalculationLogger());
            var result = service.PerformCalculation(type, p1, p2);

            Assert.False(result.Success);
        }
        public IActionResult Division([Bind] string nums)
        {
            var serv   = new CalculatorService();
            var result = serv.Division(nums);

            return(Ok(result));
        }
        private void TestMinus(int num1, int num2, int expect)
        {
            var calculatorService = new CalculatorService();
            var actual            = calculatorService.Minus(num1, num2);

            Assert.AreEqual(expect, actual);
        }
Exemplo n.º 15
0
        public void CalculatorDividByZero(string expression)
        {
            var calculator = new CalculatorService();
            var result     = calculator.CalculateExpression(expression);

            Assert.Equal(result, Double.PositiveInfinity);
        }
Exemplo n.º 16
0
        public void TestDivideBy0()
        {
            var expression = "10/ 0";
            var actual     = new CalculatorService().Calculate(expression);

            Assert.AreEqual(false, actual.HasValue, "TestDivideBy0 passed");
        }
Exemplo n.º 17
0
        private int CalculatorServiceAdd(int num1, int num2)
        {
            var calculatorService = new CalculatorService();
            var actual            = calculatorService.Add(num1, num2);

            return(actual);
        }
Exemplo n.º 18
0
        public void Calculate_PassesValidation_ReturnsExpectedResult()
        {
            // Arrange
            var calculatorService = new CalculatorService(_logger.Object);
            var calculation       = new Mock <ICalculation <decimal> >(MockBehavior.Strict);

            var validationResult = new ValidationResult {
                IsValid = true
            };

            calculation.Setup(x => x.Validate()).Returns(validationResult);
            calculation.Setup(x => x.Calculate()).Returns(0.55M);
            calculation.Setup(x => x.GetInputsForLogMessage()).Returns("SomeInputs");

            // Act
            var result = calculatorService.Calculate(calculation.Object);

            // Assert
            var expected = new CalculationResult <decimal>
            {
                Value      = 0.55M,
                Validation = validationResult
            };

            result.Should().BeEquivalentTo(expected);
            calculation.Verify(x => x.Validate(), Times.Once);
            calculation.Verify(x => x.Calculate(), Times.Once);
            _logger.VerifyInformationWasCalled("[CALCULATION] Type: ICalculation`1Proxy | Inputs: SomeInputs | Result: 0.55");
        }
        public void OperationsLocked()
        {
            IConfigurationStore configurationStore = new DefaultConfigurationStore();

            MutableConfiguration facNode = new MutableConfiguration("facility");

            facNode.Attributes["id"]   = "slow";
            facNode.Attributes["type"] = "Castle.Windsor.Tests.Facilities.SlowlyInitFacility, Castle.Windsor.Tests";

            configurationStore.AddFacilityConfiguration("slow", facNode);

            MutableConfiguration compNode = new MutableConfiguration("component");

            compNode.Attributes["id"]   = "a";
            compNode.Attributes["type"] = "Castle.Windsor.Tests.Components.CalculatorService, Castle.Windsor.Tests";

            configurationStore.AddComponentConfiguration("a", compNode);

            AsyncInitializationContainer container = new AsyncInitializationContainer(configurationStore);

            Assert.AreEqual(1, container.Kernel.GraphNodes.Length);
            Assert.AreEqual(1, container.Kernel.GraphNodes.Length);

            CalculatorService service = (CalculatorService)
                                        container[typeof(CalculatorService)];

            Assert.IsNotNull(service);
            service = (CalculatorService)
                      container[typeof(CalculatorService)];
        }
Exemplo n.º 20
0
        public void DevideTest()
        {
            var calService = new CalculatorService();
            var resultSum  = calService.Divide(9, 3);

            Assert.Equal(3, resultSum);
        }
Exemplo n.º 21
0
        public void Xml_hook_and_selector()
        {
            ProxyAllHook.Instances      = 0;
            SelectAllSelector.Calls     = 0;
            SelectAllSelector.Instances = 0;
            container.Install(XmlResource("interceptorsWithHookAndSelector.xml"));
            var model   = container.Kernel.GetHandler("ValidComponent").ComponentModel;
            var options = model.ObtainProxyOptions(false);

            Assert.IsNotNull(options);
            Assert.IsNotNull(options.Selector);
            Assert.IsNotNull(options.Hook);
            Assert.AreEqual(0, SelectAllSelector.Instances);
            Assert.AreEqual(0, ProxyAllHook.Instances);

            service = container.Resolve <CalculatorService>("ValidComponent");

            Assert.AreEqual(1, SelectAllSelector.Instances);
            Assert.AreEqual(0, SelectAllSelector.Calls);
            Assert.AreEqual(1, ProxyAllHook.Instances);

            service.Sum(2, 2);

            Assert.AreEqual(1, SelectAllSelector.Calls);
        }
Exemplo n.º 22
0
        public void SumTest(int firstNumber, int secondNumber, int expectedResult)
        {
            var calService = new CalculatorService();
            var resultSum  = calService.Sum(firstNumber, secondNumber);

            Assert.Equal(expectedResult, resultSum);
        }
Exemplo n.º 23
0
        public void Calculate_WhenParamsEqual_5MinsUnits_2MilesUnits_2010_10_08_5_30PM_ToEqual_975Fare_ReturnsJsonResult()
        {
            //arrange
            var service    = new CalculatorService();
            var controller = new CalculatorController(service);

            AngularJS.Cab.Fare.Calculator.Models.CabFareModel input = new AngularJS.Cab.Fare.Calculator.Models.CabFareModel()
            {
                numMinutesAbove6mph = 5,
                numMilesBelow6mph   = 2,
                dateOfTrip          = new DateTime(2010, 10, 8),
                timeOfTrip          = DateTime.ParseExact("17:30:00", "HH:mm:ss", CultureInfo.InvariantCulture),
                minuteUnit          = 0,
                mileUnit            = 0,
                nightCharge         = 0,
                weekDayCharge       = 0,
                totalUnitsFee       = 0,
                totalFare           = 0
            };

            //perform the action
            var actual = controller.Index(input);

            //assert
            Assert.IsInstanceOfType(actual, typeof(JsonResult), "Should have returned a JsonResult");
            var jsonResult = (JsonResult)actual;

            Assert.IsInstanceOfType(jsonResult.Data, typeof(CabFareModel), "Data not able ton convert to CabFareModel");
            var model = (CabFareModel)jsonResult.Data;

            Assert.AreEqual(9.75, model.totalFare, "The total fare is wrong");
        }
Exemplo n.º 24
0
 // Constructor
 public CalculateCommand(CalculatorService calculator,
                         char @operator, int operand)
 {
     _calculator = calculator;
     _operator   = @operator;
     _operand    = operand;
 }
Exemplo n.º 25
0
        protected async Task HandleValidSubmit()
        {
            try
            {
                CalculationStatus = new CalculationStatusViewModel();
                IsCalculating     = true;

                var jobId = await CalculatorService.StartCalculation(CalculationRequest);

                await Task.Run(() => // TODO: make it cancelable !
                {
                    CalculationResponse statusObject;
                    do
                    {
                        statusObject               = CalculatorService.GetCalculationStatus(jobId).Result;
                        CalculationStatus.Status   = statusObject.Status.ToString();
                        CalculationStatus.Progress = $"{ statusObject.Progress } %";
                        InvokeAsync(() => StateHasChanged());
                    } while (statusObject.Status == Models.CalculationStatus.Running);

                    if (statusObject.Status == Models.CalculationStatus.Completed)
                    {
                        CalculationStatus.Outcome = statusObject.Outcome;
                    }
                });
            }
            finally
            {
                IsCalculating = false;
                StateHasChanged();
            }
        }
Exemplo n.º 26
0
        public void TesVariousDelimetrs()
        {
            string pattern = @"-?\d+";
            string input   = "//***\ndsada1fds***2***10”,3,4,2000,";
            var    matches = Regex.Matches(input, pattern);

            StringBuilder positiveNumberList = new StringBuilder();

            for (int i = 0; i < matches.Count; i++)
            {
                int result = 0;

                if (!string.IsNullOrEmpty(matches[i].ToString()) && int.TryParse(matches[i].ToString(), out result) && result > 0 && result <= 1000)
                {
                    positiveNumberList.Append(result + ",");
                }
            }

            int expected = 20;


            CalculatorService calculatorService = new CalculatorService();
            int actual = calculatorService.Add(positiveNumberList.ToString().TrimEnd(','));

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Efficiency(string core, string speedUp)
        {
            var result = new Efficiency();

            using (var client = new HttpClient())
            {
                var request = CalculatorService.GetRequestEfficiency(core, speedUp);
                var content = new StringContent(request, Encoding.UTF8, "text/xml");
                var action  = "http://tempuri.org/ICalculator/Efficiency";

                client.DefaultRequestHeaders.Add("SOAPAction", action);

                using (var response = await client.PostAsync(CalculatorService.Url, content))
                {
                    var asyncstring = await response.Content.ReadAsStringAsync();

                    var soapResponse = Transform.Exec(asyncstring);
                    var serialize    = JsonConvert.DeserializeObject <EfficiencyRoot>(soapResponse);

                    result.Calculated = serialize.Envelope.Body.EfficiencyResponse.EfficiencyResult.Calculated;
                }
            }

            return(Ok(result));
        }
Exemplo n.º 28
0
        public async void Calculator_CalculatesPrices()
        {
            var discounterFactory = new Mock <IDiscounterFactory>();
            var calculator        = new CalculatorService(discounterFactory.Object);
            var products          = new List <Product>()
            {
                new Product {
                    Name = "bread", Quantity = 1, Price = new Price {
                        Amount = 1.00m
                    }
                },
                new Product {
                    Name = "butter", Quantity = 1, Price = new Price {
                        Amount = 0.8m
                    }
                },
                new Product {
                    Name = "milk", Quantity = 1, Price = new Price {
                        Amount = 1.15m
                    }
                }
            };
            var basket = new Basket
            {
                Products = products
            };

            discounterFactory
            .Setup(f => f.GetDiscounter(It.IsAny <Product>()))
            .Returns <IDiscounterService>(null);

            var receipt = await calculator.Calculate(basket);

            Assert.True(receipt.Total == 2.95m);
        }
Exemplo n.º 29
0
        public CalculatorService Init(out MockConfig mockConfig)
        {
            mockConfig = new MockConfig();
            var service = new CalculatorService();

            return(service);
        }
        public void DifferentMarginTest()
        {
            var request = new Request();
            request.ProductHierarchy = new List<Relation>(this.hierarchy);
            request.GeographyHierarchy = new List<Relation>(this.hierarchy);
            request.SalesComponentHierarchy = new List<Relation>(this.hierarchy);
            request.PeriodHierarchy = new List<Relation>();

            request.Sales = new List<ConcreteFact>();
            request.Sales.AddRange(makeDuetos(4, 7, 4, 7, 4, 7, 1, 10, 100));

            //including facts for each period
            request.Margins = Enumerable.Range(1, 10).SelectMany(r =>
                {
                    var facts = new List<NullableFact>();
                    facts.Add(new NullableFact() { TimeId = (short)r, ProductId = 2, Value = 0.15f });
                    facts.Add(new NullableFact() { TimeId = (short)r, ProductId = 3, Value = 0.25f });
                    return facts;
                }).ToList();

            request.Spend = new List<NullableFact>() { new NullableFact() { ProductId = 1, GeographyId = 1, Value = 100 } };

            // no adjustments
            request.Adjustments = null;

            var calculator = new CalculatorService();
            var result = calculator.CalculateRoi(request);

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(128f, result.Single().Value, 0.0001);
        }
Exemplo n.º 31
0
        internal int Calculate()
        {
            var calculator = new CalculatorService(this);

            calculator.Run();
            return(this.result);
        }
Exemplo n.º 32
0
        public void ImplementsICalculatorService(CalculatorService service)
        {
            // -- Arrange

            // -- Act

            // -- Assert
            Assert.IsAssignableFrom<ICalculatorService>(service);
        }
        public void Run_NotSupportedOperation_Test()
        {
            var userInterfaceMock = new Mock<IUserInterface>();
            userInterfaceMock.Setup(c => c.ReadModel()).Returns(new MathematicModel { First = 5, Second = 2, Operation = (Operations)3});

            var calculatorService = new CalculatorService(new Mock<IMathematics>().Object, userInterfaceMock.Object);

            Assert.Throws<NotSupportedException>(() => calculatorService.Run());
        }
        public void Run_Test()
        {
            var mathematicsMock = new Mock<IMathematics>();
            mathematicsMock.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>())).Returns(100);
            mathematicsMock.Setup(m => m.Subtract(It.IsAny<int>(), It.IsAny<int>())).Returns(1);

            var userInterfaceMock = new Mock<IUserInterface>();
            userInterfaceMock.Setup(c => c.ReadModel()).Returns(new MathematicModel { First = 5, Second = 2 });
            userInterfaceMock.Setup(c => c.WriteResult(100)).Verifiable("Output of add operation should be written to the ui");

            var calculatorService = new CalculatorService(mathematicsMock.Object, userInterfaceMock.Object);

            calculatorService.Run();

            userInterfaceMock.VerifyAll();
        }
Exemplo n.º 35
0
        public void CalculatesASimpleEquation(
            string[] input,
            decimal expected,
            [Frozen] Mock<IFile> fileMock,
            [Frozen(Matching.ImplementedInterfaces)] FileParser parser,
            [Frozen(Matching.ImplementedInterfaces)] CruncherAutomator cruncher,
            CalculatorService calculator)
        {
            // -- Arrange
            fileMock.Setup(m => m.ReadAllLines(It.IsAny<string>())).Returns(input);

            // -- Act
            var actual = calculator.Process(@"C:\fakePath.input");

            // -- Assert
            Assert.Equal(expected, actual);
        }
        public void IntegratedCalculateRoi_BasicTest()
        {
            var request = new Request();
            request.ProductHierarchy = new List<Relation>(this.hierarchy);
            request.GeographyHierarchy = new List<Relation>(this.hierarchy);
            request.SalesComponentHierarchy = new List<Relation>();
            request.PeriodHierarchy = new List<Relation>();

            request.Sales = new List<ConcreteFact>();
            request.Sales.AddRange(makeDuetos(2, 2, 2, 2, 1, 1, 1, 10, 100));

            request.Margins = Enumerable.Range(1, 10).Select(r => new NullableFact() { Value = 0.15f, TimeId = (short)r }).ToList();
            request.Spend = new List<NullableFact>() { new NullableFact() { ProductId = 1, GeographyId = 1, Value = 100 } };

            // no adjustments
            request.Adjustments = null;

            var calculator = new CalculatorService();
            var result = calculator.CalculateRoi(request);

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(1.5f, result.Single().Value, 0.0001);
        }
        public void IntegratedTest()
        {
            var request = new Request();
            request.ProductHierarchy = new List<Relation>(this.hierarchy);
            request.GeographyHierarchy = new List<Relation>(this.hierarchy);
            request.SalesComponentHierarchy = new List<Relation>();
            request.PeriodHierarchy = new List<Relation>();

            request.Sales = new List<ConcreteFact>();
            request.Sales.AddRange(makeDuetos(4, 7, 4, 7, 4, 7, 1, 10, 100));

            request.Margins = new List<NullableFact>() { new NullableFact() { Value = 0.15f } };
            request.Spend = new List<NullableFact>() { new NullableFact() { ProductId = 1, GeographyId = 1, Value = 100 } };

            var calculator = new CalculatorService();

            var adjustments = new List<NullableFact>();

            for (short g = 4; g <= 7; g++)
            for (short s = 4; s <= 7; s++)
            {
                adjustments.Add(new NullableFact() { GeographyId = g, SalesComponentId = s, Value = 1.5f });
            }

            request.Adjustments = new List<Adjustment>() { new Adjustment() { AdjustmentType = AdjustmentType.Adjustment, Facts = adjustments } };
            var result = calculator.CalculateRoi(request);

            // Missing assert
            Assert.Fail();
        }
        public void DifferentMarginTest_WithDiscreteGaps()
        {
            var request = new Request();
            request.ProductHierarchy = new List<Relation>(this.hierarchy);
            request.GeographyHierarchy = new List<Relation>(this.hierarchy);
            request.SalesComponentHierarchy = new List<Relation>(this.hierarchy);
            request.PeriodHierarchy = new List<Relation>();

            request.Sales = new List<ConcreteFact>();
            request.Sales.AddRange(makeDuetos(4, 7, 4, 7, 4, 7, 1, 10, 1));

            // no product 7 in geog 7
            // will exclude for all 4 sales components x 10 weeks (40 leaf)
            request.Sales.RemoveAll(d => d.ProductId == 7 && d.GeographyId == 7);

            // causal 6 not run in geogs 4,5
            // will exclude for all 4 products x 10 weeks in both geogs (80 leaf)
            request.Sales.RemoveAll(d => d.SalesComponentId == 6 && (d.GeographyId == 4 || d.GeographyId == 5));

            //including facts for each period
            request.Margins = Enumerable.Range(1, 10).SelectMany(r =>
            {
                var facts = new List<NullableFact>();
                facts.Add(new NullableFact() { TimeId = (short)r, ProductId = 2, Value = 0.15f });
                facts.Add(new NullableFact() { TimeId = (short)r, ProductId = 3, Value = 0.25f });
                return facts;
            }).ToList();

            request.Spend = new List<NullableFact>() { new NullableFact() { ProductId = 1, GeographyId = 1, Value = 100 } };

            // no adjustments
            request.Adjustments = null;

            var calculator = new CalculatorService();
            var result = calculator.CalculateRoi(request);

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(1.02f, result.Single().Value, 0.0001);
        }