Esempio n. 1
0
 private InvoicePartyInfo(NonNegativeInt?branch = null, TaxpayerIdentificationNumber taxIdentifier = null, string name = null, Address address = null)
 {
     Branch        = branch ?? NonNegativeInt.Zero();
     TaxIdentifier = taxIdentifier.ToOption();
     Name          = name.ToOption();
     Address       = address.ToOption();
 }
Esempio n. 2
0
 internal static InvoiceParty CreateInvoiceParty(Country country, string taxNumber, string name = null, Address address = null)
 {
     return(InvoiceParty.Create(
                info: InvoicePartyInfo.Create(NonNegativeInt.Zero(), TaxpayerIdentificationNumber.Create(country, taxNumber).Success.Get(), name, address).Success.Get(),
                country: country
                ).Success.Get());
 }
        public Property MaxValue_CannotBe_NegativeOrZero(NonNegativeInt maxLevel)
        {
            var result = Level.New(-maxLevel.Get, 0);

            return((result is Error <Level, LevelError> error && ((LevelError)error) is LevelError.NegativeOrZeroMaxLevelError)
                   .ToProperty());
        }
        private async Task PerformTest(UserType userType)
        {
            this.apiKeyRepository.Setup(v => v.GetApiKey(userType)).Returns(ApiKey);

            var expectedInput = new CreateRefundIn
            {
                Amount   = AmountInMinorDenomination.Create(RefundCreditAmount).ToMajorDenomination(),
                CustomId = CreateTaxamoTransaction.CustomId
            };

            CreateRefundIn actualInput = null;

            this.taxamoService.Setup(v => v.CreateRefundAsync(TaxamoTransactionKey, It.IsAny <CreateRefundIn>(), ApiKey))
            .Callback <string, CreateRefundIn, string>((a, b, c) => actualInput = b)
            .ReturnsAsync(new CreateRefundOut
            {
                TotalAmount = 0.12m,
                TaxAmount   = 0.02m,
            });

            var result = await this.target.ExecuteAsync(TaxamoTransactionKey, RefundCreditAmount, userType);

            Assert.AreEqual(
                new CreateTaxamoRefund.TaxamoRefundResult(
                    PositiveInt.Parse(12),
                    NonNegativeInt.Parse(2)),
                result);

            Assert.AreEqual(
                JsonConvert.SerializeObject(expectedInput, Formatting.None),
                JsonConvert.SerializeObject(actualInput, Formatting.None));
        }
Esempio n. 5
0
        public void ItShouldBePossibleToImplicitlyCastNonNegativeIntToNonNegativeDecimal()
        {
            var value = Extensions.GetValue(() => NonNegativeInt.TryCreate(1, (NonEmptyString)"Value"));
            NonNegativeDecimal castResult = value;

            castResult.ShouldBeOfType <NonNegativeDecimal>();
        }
        public Property Level_CannotBe_NegativeOrZero(NonNegativeInt level)
        {
            var result = Level.New(5, -level.Get);

            return((result is Error <Level, LevelError> error && ((LevelError)error) is LevelError.NegativeOrZeroLevelError)
                   .ToProperty());
        }
 public Task Execute(
     UserId userId,
     UserId creatorId,
     IReadOnlyList <ChannelId> channelIds,
     IReadOnlyList <QueueId> collectionIds,
     DateTime origin,
     bool searchForwards,
     NonNegativeInt startIndex,
     PositiveInt count,
     IReadOnlyList <NewsfeedPost> expectedPosts,
     int expectedAccountBalance)
 {
     expectedPosts = this.GetPostsForUser(expectedPosts, userId);
     return(this.parameterizedTest(
                userId,
                creatorId,
                channelIds,
                collectionIds,
                origin,
                searchForwards,
                startIndex,
                count,
                expectedPosts,
                expectedAccountBalance));
 }
 public InvoiceParty(Country country, NonEmptyString taxIdentifier = null, NonNegativeInt branch = null, string name = null, Address address = null)
 {
     TaxIdentifier = taxIdentifier ?? new NonEmptyString("0");
     Country       = country ?? throw new ArgumentNullException(nameof(country));
     Branch        = branch ?? new NonNegativeInt(0);
     Name          = name;
     Address       = address;
 }
Esempio n. 9
0
            public void ThrowsWhenHorizonIsLowerOrEqualToZero(NonNegativeInt slotsPerWindow)
            {
                var timeService = Substitute.For <ITimeService>();

                Action creatingLeakyBucket = () => new LeakyBucket(timeService, -slotsPerWindow.Get);

                creatingLeakyBucket.Should().Throw <ArgumentOutOfRangeException>();
            }
Esempio n. 10
0
 public InvoiceParty(StringIdentifier taxNumber, CountryCode countryCode, NonNegativeInt branch = null, StringIdentifier name = null, Address address = null)
 {
     TaxNumber   = taxNumber ?? throw new ArgumentNullException(nameof(taxNumber));
     CountryCode = countryCode ?? throw new ArgumentNullException(nameof(countryCode));
     Branch      = branch ?? new NonNegativeInt(0);
     Name        = name;
     Address     = address;
 }
Esempio n. 11
0
            public void ThrowsWhenTheLengthIsAZeroOrLess(NonNegativeInt number, NonNegativeInt length)
            {
                var nonPositiveLength = -1 * length.Get;

                Action withNegativeNumber = () => number.Get.PingPongClamp(nonPositiveLength);

                withNegativeNumber.Should().Throw <ArgumentOutOfRangeException>();
            }
 public InvoiceRecordParty(VatIdentifier vatNumber, NonNegativeInt branch, StringIdentifier name, CountryCode countryCode, InvoiceRecordPartyAddress invoiceRecordPartyAddress)
 {
     VatNumber   = vatNumber ?? throw new ArgumentNullException(nameof(vatNumber));
     Branch      = branch ?? throw new ArgumentNullException(nameof(branch));
     Name        = name;
     CountryCode = countryCode ?? throw new ArgumentNullException(nameof(countryCode));
     Address     = invoiceRecordPartyAddress;
 }
Esempio n. 13
0
        public Property collect_weekday_name(Date anyDate, Zone anyZone, NonNegativeInt total)
        {
            var days = Time.FromDays((int)total);

            var addThenShift = Zone.ConvertTime(anyDate + days, anyZone);
            var shiftThenAdd = Zone.ConvertTime(anyDate, anyZone) + days;

            return((addThenShift == shiftThenAdd).Collect(anyDate.DayOfWeekName()));
        }
Esempio n. 14
0
        public Property trivial_daylight_savings_support(Date anyDate, Zone anyZone, NonNegativeInt total)
        {
            var days = Time.FromDays((int)total);

            var addThenShift = Zone.ConvertTime(anyDate + days, anyZone);
            var shiftThenAdd = Zone.ConvertTime(anyDate, anyZone) + days;

            return((addThenShift == shiftThenAdd).Trivial(anyZone.SupportsDaylightSavingTime));
        }
Esempio n. 15
0
        public void ReturnsEquivalentImageForAnyRadiusIfImageIsSinglePixel(NonNegativeInt radius, int seed)
        {
            var bitmap  = randomBitmap(1, 1, seed);
            var blurrer = CreateBlurrerWith(radius.Get);

            var returnedBitmap = blurrer.Apply(bitmap);

            bitmapsShouldBeEquivalent(bitmap, returnedBitmap);
        }
Esempio n. 16
0
            public void SetsTheMonthTo1IfMonthIs12(NonNegativeInt nonNegativeInt)
            {
                var year          = nonNegativeInt.Get;
                var calendarMonth = new CalendarMonth(year, 12);

                var nextCalendarMonth = calendarMonth.Next();

                nextCalendarMonth.Month.Should().Be(1);
            }
Esempio n. 17
0
            public void IncreasesTheYearIfMonthIs12(NonNegativeInt nonNegativeInt)
            {
                var year          = nonNegativeInt.Get;
                var calendarMonth = new CalendarMonth(year, 12);

                var nextCalendarMonth = calendarMonth.Next();

                nextCalendarMonth.Year.Should().Be(year + 1);
            }
Esempio n. 18
0
            public void AlwaysIsAMultipleOf7(
                NonNegativeInt year,
                NonNegativeInt month,
                BeginningOfWeek beginingOfWeek)
            {
                prepare(year.Get % 9999 + 2, month.Get % 12 + 1, beginingOfWeek);

                (viewModel.Days.Count % 7).Should().Be(0);
            }
Esempio n. 19
0
        public bool ShorteningWithElipsis(NonNull <string> text, NonNegativeInt maxLength, NonNull <string> elipsis)
        {
            return(text.Get.Shorten(maxLength.Get, elipsis.Get) switch
            {
                var shorten when text.Get.Length <= maxLength.Get => shorten == text.Get,

                var shorten when maxLength.Get <= elipsis.Get.Length => elipsis.Get.StartsWith(shorten),

                var shorten => shorten == text.Get.Substring(0, maxLength.Get - elipsis.Get.Length) + elipsis.Get,
            });
        public void NonNegativeIntValidatesCorrectly(int value, bool isSuccess)
        {
            Assert.AreEqual(isSuccess, NonNegativeInt.Create(value).IsSuccess);

            var exceptionConstraint = isSuccess.Match <IConstraint>(
                t => Throws.Nothing,
                f => Throws.TypeOf <ArgumentException>()
                );

            Assert.That(() => NonNegativeInt.CreateUnsafe(value), exceptionConstraint);
        }
Esempio n. 21
0
        public Property classify_meridian_position(Date anyDate, Zone anyZone, NonNegativeInt total)
        {
            var days = Time.FromDays((int)total);

            var addThenShift = Zone.ConvertTime(anyDate + days, anyZone);
            var shiftThenAdd = Zone.ConvertTime(anyDate, anyZone) + days;

            return((addThenShift == shiftThenAdd)
                   .Classify(anyDate.Offset < Time.Zero, "West of Greenwich")
                   .Classify(anyDate.Offset == Time.Zero, "Within Greenwich")
                   .Classify(anyDate.Offset > Time.Zero, "East of Greenwich"));
        }
Esempio n. 22
0
        public Property Correct_K_Clusters(PositiveInt unique, NonNegativeInt dup, PositiveInt k)
        {
            var data = _dataGenerator.Generate((uint)unique.Get, (uint)dup.Get);

            Func <bool> property = () =>
            {
                var result = _kMeans.Clusterize(data, (uint)k.Get);

                return(result.Select(x => x.PredictedClusterId).Distinct().Count() == k.Get);
            };

            return(property.When(unique.Get >= k.Get));
        }
Esempio n. 23
0
            public void DifferenceBetweenTwoConsequentNonNegativeNumbersIsAlwaysOne(NonNegativeInt a, PositiveInt length)
            {
                if (length.Get == 1)
                {
                    return;                  // for a loop of length 1 all of the indexes will be 0
                }
                var b = a.Get + 1;

                var indexA = a.Get.PingPongClamp(length.Get);
                var indexB = b.PingPongClamp(length.Get);

                System.Math.Abs(indexA - indexB).Should().Be(1);
            }
Esempio n. 24
0
        public Property many_observations_combined(Date anyDate, Zone anyZone, NonNegativeInt total)
        {
            var days = Time.FromDays((int)total);

            var addThenShift = Zone.ConvertTime(anyDate + days, anyZone);
            var shiftThenAdd = Zone.ConvertTime(anyDate, anyZone) + days;

            return((addThenShift == shiftThenAdd)
                   .Trivial(anyZone.SupportsDaylightSavingTime)
                   .Classify(anyDate.Offset < Time.Zero, "West of Greenwich")
                   .Classify(anyDate.Offset == Time.Zero, "Within Greenwich")
                   .Classify(anyDate.Offset > Time.Zero, "East of Greenwich")
                   .Collect(anyDate.DayOfWeekName()));
        }
Esempio n. 25
0
        public bool TryExecuteSteps_WithoutFailure(NonNegativeInt stepsCount)
        {
            //arrange
            var(_, steps) = MigrationTestsContext.GenerateMigrationState(0, stepsCount);

            //act
            var(executionHistory, executionResult) = MigrationHandler.TryExecuteSteps(steps);

            var originalVersions = steps.Select(x => x.Version.ToString());
            var executedVersions = executionHistory.Reverse().Select(r => r.Version.ToString());

            //assert
            return(executionResult.Type is ExecutionResultType.Success && originalVersions.SequenceEqual(executedVersions));
        }
Esempio n. 26
0
        public bool GetSteps_HistoryIsEmpty(NonNegativeInt stepsCount)
        {
            //arrange
            var(_, steps) = MigrationTestsContext.GenerateMigrationState(stepsCount.Item, missingCount: 0);

            //act
            var result = MigrationHandler.GetSteps(steps, allHistory: new List <MigrationHistory>(), lastLegacyMigrationVersion: new Version("1.1.1.1"));

            var originalVersions = steps.Select(x => x.Version.ToString());
            var filteredVersions = result.Select(r => r.Version.ToString());

            //assert
            return(originalVersions.SequenceEqual(filteredVersions));
        }
            public void ReturnsUpToNSuggestionsWhereNIsTheNumberUsedWhenConstructingTheProvider(
                NonNegativeInt numberOfSuggestions)
            {
                var provider = new MostUsedTimeEntrySuggestionProvider(TimeService, DataSource, numberOfSuggestions.Get);

                var timeEntries = getRepeatingTimeEntries(2, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9);

                DataSource.TimeEntries
                .GetAll(Arg.Any <Func <IDatabaseTimeEntry, bool> >())
                .Returns(Observable.Return(timeEntries));

                var suggestions = provider.GetSuggestions().ToList().Wait();

                suggestions.Should().HaveCount(numberOfSuggestions.Get);
            }
Esempio n. 28
0
        public void PostValidDtoWhenNoPriorReservationsExist(
            NonNegativeInt capacitySurplus,
            PositiveInt quantity)
        {
            var repository = new FakeReservationsRepository();
            var capacity   = capacitySurplus.Item + quantity.Item;
            var sut        = new ReservationsController(repository, capacity);

            var dto = new ReservationDto
            {
                Date     = "2019-08-20",
                Quantity = quantity.Item
            };
            var actual = sut.Post(dto);

            Assert.IsAssignableFrom <OkObjectResult>(actual);
            Assert.NotEmpty(repository);
        }
Esempio n. 29
0
        public async void Property1(NonNegativeInt numberOfCalls)
        {
            int numberOfTries = 0;

            try
            {
                await new Func <Task <int> >(
                    () =>
                {
                    Interlocked.Increment(ref numberOfTries);
                    return(Task.FromException <int>(new Exception()));
                }).Retry(Enumerable.Repeat(TimeSpan.FromMilliseconds(1), numberOfCalls.Get).ToArray());
            }
            catch
            {
                Equal(numberOfCalls.Get + 1, numberOfTries);
            }
        }
Esempio n. 30
0
        public Property GetMissingSteps(NonNegativeInt present, NonNegativeInt missing)
        {
            bool Predicate()
            {
                //arrange
                var(history, steps) = MigrationTestsContext.GenerateMigrationState(present, missing);

                //act
                var result = MigrationHandler.GetMissingSteps(steps, history, steps[present.Item - 1].Version);

                var originalVersions = steps.Skip(present.Item).Select(x => x.Version.ToString());
                var filteredVersions = result.Select(r => r.Version.ToString());

                //assert
                return(originalVersions.SequenceEqual(filteredVersions));
            }

            return(new Func <bool>(Predicate).When(present.Item > 0));
        }