From 7c326e9ee9c47cb0ab7a3701d2062f715a290a8a Mon Sep 17 00:00:00 2001 From: Rich Lott / Artful Robot Date: Fri, 11 Sep 2020 14:30:33 +0100 Subject: [PATCH] Add tests for PropertyBag::setAmount() --- Civi/Payment/PropertyBag.php | 15 +++++- .../phpunit/Civi/Payment/PropertyBagTest.php | 50 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/Civi/Payment/PropertyBag.php b/Civi/Payment/PropertyBag.php index f8817b8c4e..73179edb78 100644 --- a/Civi/Payment/PropertyBag.php +++ b/Civi/Payment/PropertyBag.php @@ -417,7 +417,20 @@ class PropertyBag implements \ArrayAccess { } /** - * Get the monetary amount. + * Set the monetary amount. + * + * - We expect to be called with a string amount with optional decimals using + * a '.' as the decimal point (not a ','). + * + * - We're ok with floats/ints being passed in, too, but we'll cast them to a + * string. + * + * - Negatives are fine. + * + * @see https://github.com/civicrm/civicrm-core/pull/18219 + * + * @param string|float|int $value + * @param string $label */ public function setAmount($value, $label = 'default') { if (!is_numeric($value)) { diff --git a/tests/phpunit/Civi/Payment/PropertyBagTest.php b/tests/phpunit/Civi/Payment/PropertyBagTest.php index 0a66c6dd7c..b127f10ee4 100644 --- a/tests/phpunit/Civi/Payment/PropertyBagTest.php +++ b/tests/phpunit/Civi/Payment/PropertyBagTest.php @@ -44,6 +44,56 @@ class PropertyBagTest extends \PHPUnit\Framework\TestCase implements HeadlessInt $this->assertEquals(456, $propertyBag->getContactID('new')); } + /** + * Test we can set an amount. + * + * @see https://github.com/civicrm/civicrm-core/pull/18219 + * + * @dataProvider setAmountDataProvider + * + * @param mixed $value input + * @param mixed $expect output expected. Typically a string like '1.23' or NULL + * @param string $expectedExceptionMessage if there is one expected. + */ + public function testSetAmount($value, $expect, $expectedExceptionMessage = '') { + $propertyBag = new PropertyBag(); + try { + $propertyBag->setAmount($value); + } + catch (\Exception $e) { + if ($expectedExceptionMessage) { + $this->assertEquals($expectedExceptionMessage, $e->getMessage(), 'Expected a different exception.'); + // OK. + return; + } + // not expecting an exception, re-throw it. + throw $e; + } + $got = $propertyBag->getAmount(); + $this->assertInternalType('string', $got); + $this->assertEquals($expect, $got); + } + + /** + * + */ + public function setAmountDataProvider() { + return [ + [1, '1'], + [1.23, '1.23'], + [1.234, '1.234'], + [-1.23, '-1.23'], + ['1', '1'], + ['1.23', '1.23'], + ['1.234', '1.234'], + ['-1.23', '-1.23'], + ['1,000.23', NULL, 'setAmount requires a numeric amount value'], + ['1,000', NULL, 'setAmount requires a numeric amount value'], + ['1,23', NULL, 'setAmount requires a numeric amount value'], + ['1.230,12', NULL, 'setAmount requires a numeric amount value'], + ]; + } + /** * Test we cannot set an invalid contact ID. * -- 2.25.1