Skip to content

Commit d3d55bd

Browse files
committed
fixes for static and integration tests
1 parent d5eb78e commit d3d55bd

24 files changed

+2194
-2447
lines changed

app/code/Magento/Ups/Model/Carrier.php

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -619,8 +619,7 @@ protected function _getQuotes()
619619
"ShipperNumber" => "{$shipperNumber}",
620620
"Address" => [
621621
"AddressLine" => [
622-
"address currently no idea",
623-
"address2"
622+
"{$residentialAddressIndicator}",
624623
],
625624
"City" => "{$shipperCity}",
626625
"StateProvinceCode" => "{$shipperStateProvince}",
@@ -629,7 +628,6 @@ protected function _getQuotes()
629628
]
630629
],
631630
"ShipTo" => [
632-
"Name" => "Blank for now",
633631
"Address" => [
634632
"AddressLine" => ["{$params['49_residential']}"],
635633
"StateProvinceCode" => "{$params['destRegionCode']}",
@@ -639,7 +637,6 @@ protected function _getQuotes()
639637
]
640638
],
641639
"ShipFrom" => [
642-
"Name" => "blank for now",
643640
"Address" => [
644641
"AddressLine" => [],
645642
"StateProvinceCode" => "{$params['origRegionCode']}",
@@ -655,6 +652,9 @@ protected function _getQuotes()
655652
$rateParams['RateRequest']['Shipment']['ShipmentRatingOptions']['TPFCNegotiatedRatesIndicator'] = "Y";
656653
$rateParams['RateRequest']['Shipment']['ShipmentRatingOptions']['NegotiatedRatesIndicator'] = "Y";
657654
}
655+
if ($this->getConfigFlag('include_taxes')) {
656+
$rateParams['RateRequest']['Shipment']['TaxInformationIndicator'] = "Y";
657+
}
658658

659659
if ($serviceCode !== null) {
660660
$rateParams['RateRequest']['Shipment']['Service']['code'] = $serviceCode;
@@ -772,7 +772,7 @@ protected function _parseRestResponse($rateResponse)
772772
{
773773
$costArr = [];
774774
$priceArr = [];
775-
if ($rateResponse !== null) {
775+
if ($rateResponse !== null && strlen($rateResponse) > 0) {
776776
$rateResponseData = json_decode($rateResponse, true);
777777
if ($rateResponseData['RateResponse']['Response']['ResponseStatus']['Description'] === 'Success') {
778778
$arr = $rateResponseData['RateResponse']['RatedShipment'] ?? [];
@@ -792,8 +792,7 @@ protected function _parseRestResponse($rateResponse)
792792
$allowedCurrencies,
793793
$costArr,
794794
$priceArr,
795-
$negotiatedActive,
796-
$rateResponseData
795+
$negotiatedActive
797796
);
798797
}
799798
} else {
@@ -1549,7 +1548,6 @@ protected function _doShipmentRequest(DataObject $request)
15491548
$this->_prepareShipmentRequest($request);
15501549
$result = new DataObject();
15511550
$rawXmlRequest = $this->_formShipmentRequest($request);
1552-
//$this->setXMLAccessRequest();
15531551
$xmlRequest = $this->_xmlAccessRequest . $rawXmlRequest;
15541552
$xmlResponse = $this->_getCachedQuotes($xmlRequest);
15551553
$debugData = [];

app/code/Magento/Ups/Model/UpsAuth.php

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
use Magento\Framework\HTTP\AsyncClient\Request;
1414
use Magento\Framework\HTTP\AsyncClientInterface;
1515

16-
1716
class UpsAuth
1817
{
1918
public const TEST_AUTH_URL = 'https://wwwcie.ups.com/security/v1/oauth/token';
@@ -26,9 +25,9 @@ class UpsAuth
2625
/**
2726
* @param AsyncClientInterface|null $asyncHttpClient
2827
*/
29-
public function __construct(AsyncClientInterface $asyncHttpClient = null) {
28+
public function __construct(AsyncClientInterface $asyncHttpClient = null)
29+
{
3030
$this->asyncHttpClient = $asyncHttpClient ?? ObjectManager::getInstance()->get(AsyncClientInterface::class);
31-
3231
}
3332

3433
/**
@@ -51,17 +50,21 @@ public function getAccessToken($clientId, $clientSecret)
5150
'grant_type' => 'client_credentials',
5251
]);
5352
try {
54-
$asyncResponse = $this->asyncHttpClient->request(
55-
new Request(self::TEST_AUTH_URL, Request::METHOD_POST, $headers, $authPayload));
56-
$responseResult = $asyncResponse->get();
57-
$responseData = $responseResult->getBody();
58-
$responseData = json_decode($responseData);
53+
$asyncResponse = $this->asyncHttpClient->request(new Request(
54+
self::TEST_AUTH_URL,
55+
Request::METHOD_POST,
56+
$headers,
57+
$authPayload
58+
));
59+
$responseResult = $asyncResponse->get();
60+
$responseData = $responseResult->getBody();
61+
$responseData = json_decode($responseData);
5962
if (isset($responseData->access_token)) {
6063
$result = $responseData->access_token;
6164
} else {
6265
throw new \Magento\Framework\Exception\LocalizedException(__('Unable to retrieve access token.'));
6366
}
64-
return $result ?? '';
67+
return $result;
6568
} catch (\Magento\Framework\HTTP\AsyncClient\HttpException $e) {
6669
throw new \Magento\Framework\Exception\LocalizedException(__('Error occurred: %1', $e->getMessage()));
6770
}

app/code/Magento/Ups/Test/Unit/Model/CarrierTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@
3636
*/
3737
class CarrierTest extends TestCase
3838
{
39-
const FREE_METHOD_NAME = 'free_method';
39+
public const FREE_METHOD_NAME = 'free_method';
4040

41-
const PAID_METHOD_NAME = 'paid_method';
41+
public const PAID_METHOD_NAME = 'paid_method';
4242

4343
/**
4444
* @var Error|MockObject

dev/tests/integration/testsuite/Magento/Ups/Model/CarrierTest.php

Lines changed: 35 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ class CarrierTest extends TestCase
5656
*/
5757
private $logs = [];
5858

59+
/**
60+
* @var \Magento\Ups\Model\UpsAuth|MockObject
61+
*/
62+
private $upsAuthMock;
63+
5964
/**
6065
* @inheritDoc
6166
*/
@@ -71,7 +76,11 @@ function (string $message) {
7176
$this->logs[] = $message;
7277
}
7378
);
74-
$this->carrier = Bootstrap::getObjectManager()->create(Carrier::class, ['logger' => $this->loggerMock]);
79+
$this->upsAuthMock = $this->getMockBuilder(\Magento\Ups\Model\UpsAuth::class)
80+
->disableOriginalConstructor()
81+
->getMock();
82+
$this->carrier = Bootstrap::getObjectManager()->create(Carrier::class, ['logger' => $this->loggerMock,
83+
'upsAuth' => $this->upsAuthMock]);
7584
}
7685

7786
/**
@@ -135,18 +144,15 @@ public function testCollectFreeRates()
135144
new Response(
136145
200,
137146
[],
138-
file_get_contents(__DIR__ . "/../_files/ups_rates_response_option9.json")
147+
file_get_contents(__DIR__ . "/../_files/ups_rates_response_option5.json")
139148
)
140149
]
141150
);
142-
$upsAuthMock = $this->getMockBuilder(\Magento\Ups\Model\UpsAuth::class)
143-
->disableOriginalConstructor()
144-
->getMock();
145-
$upsAuthMock->method('getAccessToken')
146-
->willReturn('abcdefghijklmnop');
147151

152+
$this->upsAuthMock->method('getAccessToken')
153+
->willReturn('abcdefghijklmnop');
148154
$rates = $this->carrier->collectRates($request)->getAllRates();
149-
$this->assertEquals('19.19', $rates[0]->getPrice());
155+
$this->assertEquals('115.01', $rates[0]->getPrice());
150156
$this->assertEquals('03', $rates[0]->getMethod());
151157
}
152158

@@ -176,12 +182,12 @@ public function testCollectRates(int $negotiable, int $tax, int $responseId, str
176182
RateRequest::class,
177183
[
178184
'data' => [
179-
'dest_country' => 'GB',
180-
'dest_postal' => '01104',
185+
'dest_country' => 'US',
186+
'dest_postal' => '90001',
181187
'product' => '11',
182188
'action' => 'Rate',
183189
'unit_measure' => 'KGS',
184-
'base_currency' => new DataObject(['code' => 'GBP'])
190+
'base_currency' => new DataObject(['code' => 'USD'])
185191
]
186192
]
187193
);
@@ -191,7 +197,7 @@ public function testCollectRates(int $negotiable, int $tax, int $responseId, str
191197
new Response(
192198
200,
193199
[],
194-
file_get_contents(__DIR__ . "/../_files/ups_rates_response_option$responseId.xml")
200+
file_get_contents(__DIR__ . "/../_files/ups_rates_response_option$responseId.json")
195201
)
196202
]
197203
);
@@ -200,14 +206,16 @@ public function testCollectRates(int $negotiable, int $tax, int $responseId, str
200206
$this->config->setValue('carriers/ups/include_taxes', $tax, 'store');
201207
$this->config->setValue('carriers/ups/allowed_methods', $method, 'store');
202208

209+
$this->upsAuthMock->method('getAccessToken')
210+
->willReturn('abcdefghijklmnop');
203211
$rates = $this->carrier->collectRates($request)->getAllRates();
204212
$this->assertEquals($price, $rates[0]->getPrice());
205213
$this->assertEquals($method, $rates[0]->getMethod());
206214

207215
$requestFound = false;
208216
foreach ($this->logs as $log) {
209-
if (mb_stripos($log, 'RatingServiceSelectionRequest') &&
210-
mb_stripos($log, 'RatingServiceSelectionResponse')
217+
if (mb_stripos($log, 'RateRequest') &&
218+
mb_stripos($log, 'RateResponse')
211219
) {
212220
$requestFound = true;
213221
break;
@@ -246,6 +254,8 @@ public function testCollectRatesWithoutAnyAllowedMethods(): void
246254
]
247255
);
248256
$this->config->setValue('carriers/ups/allowed_methods', '', 'store');
257+
$this->upsAuthMock->method('getAccessToken')
258+
->willReturn('abcdefghijklmnop');
249259
$rates = $this->carrier->collectRates($request)->getAllRates();
250260
$this->assertInstanceOf(Error::class, current($rates));
251261
$this->assertEquals(current($rates)['carrier_title'], $this->carrier->getConfigData('title'));
@@ -260,14 +270,10 @@ public function testCollectRatesWithoutAnyAllowedMethods(): void
260270
public function collectRatesDataProvider()
261271
{
262272
return [
263-
[0, 0, 1, '11', 6.45 ],
264-
[0, 0, 2, '65', 29.59 ],
265-
[0, 1, 3, '11', 7.74 ],
266-
[0, 1, 4, '65', 29.59 ],
267-
[1, 0, 5, '11', 9.35 ],
268-
[1, 0, 6, '65', 41.61 ],
269-
[1, 1, 7, '11', 11.22 ],
270-
[1, 1, 8, '65', 41.61 ],
273+
[0, 0, 1, '03', 136.09 ],
274+
[0, 1, 2, '03', 136.09 ],
275+
[1, 0, 3, '03', 92.12 ],
276+
[1, 1, 4, '03', 92.12 ],
271277
];
272278
}
273279

@@ -289,14 +295,12 @@ public function collectRatesDataProvider()
289295
public function testRequestToShipment(): void
290296
{
291297
//phpcs:disable Magento2.Functions.DiscouragedFunction
292-
$expectedShipmentRequest = file_get_contents(__DIR__ . '/../_files/ShipmentConfirmRequest.xml');
293-
$shipmentResponse = file_get_contents(__DIR__ . '/../_files/ShipmentConfirmResponse.xml');
294-
$acceptResponse = file_get_contents(__DIR__ . '/../_files/ShipmentAcceptResponse.xml');
298+
$expectedShipmentRequest = str_replace("\n","",file_get_contents(__DIR__ . '/../_files/ShipmentConfirmRequest.json'));
299+
$shipmentResponse = file_get_contents(__DIR__ . '/../_files/ShipmentConfirmResponse.json');
295300
//phpcs:enable Magento2.Functions.DiscouragedFunction
296301
$this->httpClient->nextResponses(
297302
[
298-
new Response(200, [], $shipmentResponse),
299-
new Response(200, [], $acceptResponse)
303+
new Response(200, [], $shipmentResponse)
300304
]
301305
);
302306
$this->httpClient->clearRequests();
@@ -348,24 +352,18 @@ public function testRequestToShipment(): void
348352

349353
$requests = $this->httpClient->getRequests();
350354
$this->assertNotEmpty($requests);
351-
$shipmentRequest = $this->extractShipmentRequest($requests[0]->getBody());
355+
$shipmentRequest = $requests[0]->getBody();
352356
$this->assertEquals(
353-
$this->formatXml($expectedShipmentRequest),
354-
$this->formatXml($shipmentRequest)
357+
$expectedShipmentRequest,
358+
$shipmentRequest
355359
);
356-
357360
$this->assertEmpty($result->getErrors());
358361
$this->assertNotEmpty($result->getInfo());
359362
$this->assertEquals(
360-
'1Z207W886698856557',
363+
'1ZXXXXXXXXXXXXXXXX',
361364
$result->getInfo()[0]['tracking_number'],
362365
'Tracking Number must match.'
363366
);
364-
$this->assertEquals(
365-
'2V467W886398839541',
366-
$result->getInfo()[1]['tracking_number'],
367-
'Tracking Number must match.'
368-
);
369367
$this->httpClient->clearRequests();
370368
}
371369

@@ -411,37 +409,4 @@ public function testGetRatesWithHttpException(): void
411409

412410
$this->assertEquals($error, $resultRate);
413411
}
414-
415-
/**
416-
* Extracts shipment request.
417-
*
418-
* @param string $requestBody
419-
* @return string
420-
*/
421-
private function extractShipmentRequest(string $requestBody): string
422-
{
423-
$resultXml = '';
424-
$pattern = '%(<\?xml version="1.0"\?>\n<ShipmentConfirmRequest)(.*)$%im';
425-
if (preg_match($pattern, $requestBody, $result)) {
426-
$resultXml = array_shift($result);
427-
}
428-
429-
return $resultXml;
430-
}
431-
432-
/**
433-
* Format XML string.
434-
*
435-
* @param string $xmlString
436-
* @return string
437-
*/
438-
private function formatXml(string $xmlString): string
439-
{
440-
$xmlDocument = new \DOMDocument('1.0');
441-
$xmlDocument->preserveWhiteSpace = false;
442-
$xmlDocument->formatOutput = true;
443-
$xmlDocument->loadXML($xmlString);
444-
445-
return $xmlDocument->saveXML();
446-
}
447412
}

dev/tests/integration/testsuite/Magento/Ups/Model/UpsAuthTest.php

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,35 @@ protected function setUp(): void
3535
{
3636
$this->objectManager = Bootstrap::getObjectManager();
3737
$this->asyncHttpClientMock = Bootstrap::getObjectManager()->get(AsyncClientInterface::class);
38-
$this->upsAuth = $this->objectManager->create(UpsAuth::class, ['asyncHttpClient' => $this->asyncHttpClientMock]);
38+
$this->upsAuth = $this->objectManager->create(
39+
UpsAuth::class,
40+
['asyncHttpClient' => $this->asyncHttpClientMock]
41+
);
3942
}
4043

44+
/**
45+
* @return void
46+
* @throws \Magento\Framework\Exception\LocalizedException
47+
* @throws \Magento\Framework\Exception\NoSuchEntityException
48+
*
49+
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
50+
*/
4151
public function testGetAccessToken()
4252
{
4353
// Prepare test data
4454
$clientId = 'user';
4555
$clientSecret = 'pass';
4656

47-
// Prepare the expected request data
48-
$expectedFormData = [
49-
'grant_type' => 'client_credentials',
50-
];
51-
5257
// Prepare the expected response data
5358
$expectedAccessToken = 'abcdefghijklmnop';
54-
$responseData = '{"token_type":"Bearer","issued_at":"1690460887368","client_id":"abcdef","access_token":"abcdefghijklmnop","expires_in":"14399","status":"approved"}';
59+
$responseData = '{
60+
"token_type":"Bearer",
61+
"issued_at":"1690460887368",
62+
"client_id":"abcdef",
63+
"access_token":"abcdefghijklmnop",
64+
"expires_in":"14399",
65+
"status":"approved"
66+
}';
5567

5668
// Mock the HTTP client behavior to return a mock response
5769
$request = new Request(

0 commit comments

Comments
 (0)