public async Task WhenTaxamoAmountDoesNotEqualExpectedAmount_AndUserTypeIsTestUser_ItShouldCancelTransactionAndAbort() { this.getUserPaymentOrigin.Setup(v => v.ExecuteAsync(UserId)).ReturnsAsync(Origin); this.createTaxamoTransaction.Setup(v => v.ExecuteAsync( Amount, Origin.CountryCode, Origin.CreditCardPrefix, Origin.IpAddress, Origin.OriginalTaxamoTransactionKey, UserType.TestUser)) .ReturnsAsync(TaxamoTransaction); this.deleteTaxamoTransaction.Setup(v => v.ExecuteAsync(TaxamoTransaction.Key, UserType.TestUser)) .Returns(Task.FromResult(0)) .Verifiable(); await ExpectedException.AssertExceptionAsync <BadRequestException>( () => this.target.HandleAsync( UserId, PositiveInt.Parse(10), PositiveInt.Parse(11), UserType.TestUser)); this.deleteTaxamoTransaction.Verify(); }
public async Task ExecuteAsync( UserId enactingUserId, string stripeChargeId, PositiveInt totalRefundAmount, RefundCreditReason reason, UserType userType) { enactingUserId.AssertNotNull("enactingUserId"); stripeChargeId.AssertNotNull("stripeChargeId"); totalRefundAmount.AssertNotNull("totalRefundAmount"); var apiKey = this.apiKeyRepository.GetApiKey(userType); var options = new StripeRefundCreateOptions { Amount = totalRefundAmount.Value, Reason = this.GetReason(reason), Metadata = new Dictionary <string, string> { { EnactingUserIdMetadataKey, enactingUserId.ToString() }, } }; await this.stripeService.RefundChargeAsync(stripeChargeId, options, apiKey); }
public void ItShouldBePossibleToImplicitlyCastPositiveIntToNonNegativeDecimal() { var value = Extensions.GetValue(() => PositiveInt.TryCreate(1, (NonEmptyString)"Value")); NonNegativeDecimal castResult = value; castResult.ShouldBeOfType <NonNegativeDecimal>(); }
public async Task <TaxamoRefundResult> ExecuteAsync( string taxamoTransactionKey, PositiveInt refundCreditAmount, UserType userType) { taxamoTransactionKey.AssertNotNull("taxamoTransactionKey"); refundCreditAmount.AssertNotNull("refundCreditAmount"); var amount = AmountInMinorDenomination.Create(refundCreditAmount).ToMajorDenomination(); var apiKey = this.taxamoApiKeyRepository.GetApiKey(userType); var input = new CreateRefundIn { Amount = amount, CustomId = CreateTaxamoTransaction.CustomId, }; var result = await this.taxamoService.CreateRefundAsync(taxamoTransactionKey, input, apiKey); var totalAmount = AmountInMinorDenomination.FromMajorDenomination(result.TotalAmount.Value); var taxAmount = AmountInMinorDenomination.FromMajorDenomination(result.TaxAmount.Value); return(new TaxamoRefundResult(totalAmount.ToPositiveInt(), taxAmount.ToNonNegativeInt())); }
public bool ExistsById(PositiveInt id) { using (var connection = _dbConnectionProvider.GetOpenDbConnection()) { return(connection.QuerySingle <bool>("SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT) FROM DBO.CUSTOMERS WHERE ID = @ID", new { id = id.Value })); } }
public Property Two_durations_that_are_equal_are_equivalent(PositiveInt years, PositiveInt months, PositiveInt weeks, PositiveInt days, PositiveInt hours, PositiveInt minutes, PositiveInt seconds) { DurationExpression first = new(years.Item, months.Item, weeks.Item, days.Item, hours.Item, minutes.Item, seconds.Item); DurationExpression other = new(years.Item, months.Item, weeks.Item, days.Item, hours.Item, minutes.Item, seconds.Item); return(first.Equals(other).And(first.IsEquivalentTo(other))); }
public Property Level_CannotBe_StrictlySupperiorToMaxLevel(PositiveInt maxLevel, PositiveInt level) { var result = Level.New(maxLevel.Get, level.Get); return((level.Get > maxLevel.Get && result is Error <Level, LevelError> error && ((LevelError)error) is LevelError.LevelSupperiorToMaxError) .Or(result is Ok <Level, LevelError> ok && ((Level)ok).Max == maxLevel.Get && ((Level)ok).Value == level.Get)); }
public IβParameterElement Create( IsIndexElement sIndexElement, IrIndexElement rIndexElement, IdIndexElement dIndexElement, PositiveInt value) { IβParameterElement parameterElement = null; try { parameterElement = new βParameterElement( sIndexElement, rIndexElement, dIndexElement, value); } catch (Exception exception) { this.Log.Error( exception.Message, exception); } return(parameterElement); }
public bool Creates_Maybe_PositiveInt_Only_For_Positive_Integers(int i) { return(PositiveInt .Maybe(i) .Equals(Maybe <PositiveInt> .Nothing) .Equals(i < 0)); }
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 Maybe <Customer> Get(PositiveInt id) { using (var connection = _dbConnectionProvider.GetOpenDbConnection()) { return(connection.QuerySingleOrDefault <Customer>(SelectQuery, new { id = id.Value })); } }
public void Delete(PositiveInt id) { using (var connection = _dbConnectionProvider.GetOpenDbConnection()) { connection.Execute("DELETE FROM DBO.CUSTOMERS WHERE ID = @ID", new { id = id.Value }); } }
public IlIndexElement GetElementAt( PositiveInt day) { return(this.Value .Where(x => x.Value == day) .SingleOrDefault()); }
public async Task <InitializeCreditRequestResult> HandleAsync( UserId userId, PositiveInt amount, PositiveInt expectedTotalAmount, UserType userType) { userId.AssertNotNull("userId"); amount.AssertNotNull("amount"); var origin = await this.getUserPaymentOrigin.ExecuteAsync(userId); if (origin.PaymentOriginKey == null || origin.PaymentOriginKeyType == PaymentOriginKeyType.None) { throw new CreditCardDetailsDoNotExistException(); } // Create taxamo transaction. var taxamoTransaction = await this.createTaxamoTransaction.ExecuteAsync( amount, origin.CountryCode, origin.CreditCardPrefix, origin.IpAddress, origin.OriginalTaxamoTransactionKey, userType); // Verify expected amount matches data returned from taxamo. if (expectedTotalAmount != null && taxamoTransaction.TotalAmount.Value != expectedTotalAmount.Value) { await this.deleteTaxamoTransaction.ExecuteAsync(taxamoTransaction.Key, userType); throw new BadRequestException("The expected total amount did not match the calculated total amount."); } return(new InitializeCreditRequestResult(taxamoTransaction, origin)); }
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)); }
public Product(PositiveInt id, NonEmptyString code, NonEmptyString name, PositiveInt size) { Id = id; Code = code; Name = name; Size = size; }
public IΛIndexElement GetElementAt( PositiveInt value) { return(this.Value .Where(x => x.Value == value) .SingleOrDefault()); }
public void Multiplying_by_positive_preserves_order(PositiveInt x, SameCurrency <string> monies) { var(y, z) = monies; var x_ = (int)x; Assert.Equal(y > z, (y * x_) > (z * x_)); Assert.Equal(y > z, y.Multiply(x_) > z.Multiply(x_)); }
public LParameterElement( IsIndexElement sIndexElement, PositiveInt value) { this.sIndexElement = sIndexElement; this.Value = value; }
public void DoesNotRemoveDatesFromTheUrl(PositiveInt id) { var uri = endpoints.TimeEntries.GetBetween(DateTimeOffset.Now, DateTimeOffset.Now.AddHours(1)).Url; var anonymizedUri = uri.Anonymize(); anonymizedUri.ToString().Should().Be(uri.ToString()); }
public void RemovesIdFromTheUriWithATrailingSlash(PositiveInt id) { var uri = endpoints.Projects.Post(id.Get).Url; var anonymizedUri = uri.Anonymize(); anonymizedUri.ToString().Should().Be("https://mobile.toggl.space/api/v9/workspaces/{id}/projects"); }
public BParameterElement( IjIndexElement jIndexElement, PositiveInt value) { this.jIndexElement = jIndexElement; this.Value = value; }
public void DoesNotRemoveTimestampFromTheUrl(PositiveInt id) { var uri = endpoints.TimeEntries.GetSince(DateTimeOffset.Now).Url; var anonymizedUri = uri.Anonymize(); anonymizedUri.ToString().Should().Be(uri.ToString()); }
public Maybe <NonEmptyString> GetRowVersionById(PositiveInt id) { using (var connection = _dbConnectionProvider.GetOpenDbConnection()) { var result = connection.QuerySingleOrDefault <byte[]>("SELECT VERSION FROM DBO.CUSTOMERS WHERE ID = @ID", new { id = id.Value }); return(result != null ? (NonEmptyString)Convert.ToBase64String(result) : null); } }
public Property Equals_depends_on_values_only(PositiveInt years, PositiveInt months, PositiveInt weeks, PositiveInt days, PositiveInt hours, PositiveInt minutes, PositiveInt seconds) { DurationExpression first = new(years.Item, months.Item, weeks.Item, days.Item, hours.Item, minutes.Item, seconds.Item); DurationExpression other = new(years.Item, months.Item, weeks.Item, days.Item, hours.Item, minutes.Item, seconds.Item); return(first.Equals(other).Label("Equality") .And(first.GetHashCode() == other.GetHashCode()).Label("Hashcode")); }
public bool Creates_Result_PositiveInt_Only_For_Positive_Integers(int i) { return(PositiveInt .Result(i) .GetOk() .Equals(Maybe <PositiveInt> .Nothing) .Equals(i < 0)); }
public THRParameterElement( IpIndexElement pIndexElement, PositiveInt value) { this.pIndexElement = pIndexElement; this.Value = value; }
public Property UniqueItems(PositiveInt x, PositiveInt y, PositiveInt z) { Spec <PositiveInt[]> spec = Spec.Of <PositiveInt[]>().Unique("should only include unique items"); return(spec.ToProperty(new[] { x, y, z }) .When(x.Get != y.Get && x.Get != z.Get && y.Get != z.Get) .And(spec.ToProperty(Array.Empty <PositiveInt>()))); }
public void Set_Retry_Info_When_SendingPMode_Is_Configured_For_Retry( bool enabled, PositiveInt count, TimeSpan interval) { // Arrange ClearOutExceptions(); var sut = new OutboundExceptionHandler(GetDataStoreContext, StubConfig.Default, new InMemoryMessageBodyStore()); var pmode = new SendingProcessingMode(); pmode.ExceptionHandling.Reliability = new RetryReliability { IsEnabled = enabled, RetryCount = count.Get, RetryInterval = interval.ToString("G") }; var entity = new OutMessage($"entity-{Guid.NewGuid()}"); GetDataStoreContext.InsertOutMessage(entity); // Act sut.HandleExecutionException( new Exception(), new MessagingContext( new ReceivedEntityMessage(entity), MessagingContextMode.Notify) { SendingPMode = pmode }) .GetAwaiter() .GetResult(); // Assert GetDataStoreContext.AssertOutException(ex => { Assert.Null(ex.MessageLocation); GetDataStoreContext.AssertRetryRelatedOutException( ex.Id, rr => { Assert.True( enabled == (0 == rr?.CurrentRetryCount), "CurrentRetryCount != 0 when RetryReliability is enabled"); Assert.True( enabled == (count.Get == rr?.MaxRetryCount), enabled ? $"Max retry count failed on enabled: {count.Get} != {rr?.MaxRetryCount}" : $"Max retry count should be 0 on disabled but is {rr?.MaxRetryCount}"); Assert.True( enabled == (interval == rr?.RetryInterval), enabled ? $"Retry interval failed on enabled: {interval:G} != {rr?.RetryInterval}" : $"Retry interval should be 0:00:00 on disabled but is {rr?.RetryInterval}"); }); }); }
public static Maybe <Person> Maybe(NonEmptyString name, PositiveInt age) { return(NotNull(name) .And(NotNull(age)) .And(() => name.Text.Matches("^[a-zA-Z\\. ]+$")) .And(() => age.Number.ExclusiveBetween(0, 100)) .ThenMaybe(name.TupleWith(age)) .Select(t => new Person(t.Item1, t.Item2))); }
public void TestCommandHistory() { PositiveInt x = new PositiveInt(); CommandHistory test = new CommandHistory(); // test initial state Assert.IsTrue(!test.CanUndo); Assert.IsTrue(!test.CanRedo); Assert.IsTrue(!test.Dirty); // test adding command Command cmd = new IncCommand(x); test.Add(cmd); cmd.Do(); Assert.IsTrue(x.Value == 1); Assert.IsTrue(test.CanUndo); Assert.IsTrue(!test.CanRedo); Assert.IsTrue(test.Dirty); test.Undo(); Assert.IsTrue(x.Value == 0); Assert.IsTrue(!test.CanUndo); Assert.IsTrue(test.CanRedo); Assert.IsTrue(!test.Dirty); test.Redo(); Assert.IsTrue(x.Value == 1); Assert.IsTrue(test.CanUndo); Assert.IsTrue(!test.CanRedo); Assert.IsTrue(test.Dirty); test.Dirty = false; Assert.IsTrue(!test.Dirty); cmd = new IncCommand(x); test.Add(cmd); cmd.Do(); Assert.IsTrue(test.Dirty); test.Undo(); Assert.IsTrue(!test.Dirty); test.Dirty = true; Assert.IsTrue(test.Dirty); }
public void TestCompositeCommand() { PositiveInt x = new PositiveInt(); CompositeCommand composite1 = new CompositeCommand("1", new Command[] { new IncCommand(x), new IncCommand(x) }); composite1.Do(); Assert.IsTrue(x.Value == 2); composite1.Undo(); Assert.IsTrue(x.Value == 0); CompositeCommand composite2 = new CompositeCommand("1", new Command[] { new IncCommand(x), new DecCommand(x), new DecCommand(x) }); // Try to execute a composite that will cause an exception try { composite2.Do(); Assert.Fail(); } catch { } Assert.IsTrue(x.Value == 0); // make sure command was backed out }
public DecCommand(PositiveInt target) : base("DecCommand") { this.target = target; }