Bug 1440041 - mochitest for nsIPaymentRequest.shippingOption. r=baku
authorEden Chuang <chenyu.chuang@gapp.nthu.edu.tw>
Fri, 13 Apr 2018 18:48:31 -0700
changeset 413319 f07f19c30db9
parent 413318 8b12f74a216d
child 413320 b329a07c07b4
push id102139
push usermozilla@noorenberghe.ca
push dateSat, 14 Apr 2018 04:54:11 +0000
treeherdermozilla-inbound@f07f19c30db9 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbaku
bugs1440041, 1443914
milestone61.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1440041 - mochitest for nsIPaymentRequest.shippingOption. r=baku This patch includes followings 1. Test with no selected shipping options. 2. Test with one selected shipping option when creating PaymentRequest. 3. Test with multiple selected shipping options when creating PaymentRequest. 4. Test with selecting shipping option by user. 5. Test with modifying the user selection by merchant. 6. Merges the mochitest for bug 1443914.
dom/payments/test/Bug1443914ChromeScript.js
dom/payments/test/DefaultData.js
dom/payments/test/ShippingOptionsChromeScript.js
dom/payments/test/mochitest.ini
dom/payments/test/test_bug1443914.html
dom/payments/test/test_shippingOptions.html
new file mode 100644
--- /dev/null
+++ b/dom/payments/test/DefaultData.js
@@ -0,0 +1,50 @@
+// testing data declation
+const defaultMethods = [{
+  supportedMethods: "basic-card",
+  data: {
+    supportedNetworks: ['unionpay', 'visa', 'mastercard', 'amex', 'discover',
+                        'diners', 'jcb', 'mir',
+    ],
+    supportedTypes: ['prepaid', 'debit', 'credit'],
+  },
+}, {
+  supportedMethods: "testing-payment-method",
+}];
+
+const defaultDetails = {
+  total: {
+    label: "Total",
+    amount: {
+      currency: "USD",
+      value: "1.00",
+    }
+  },
+  shippingOptions: [
+    {
+      id: "NormalShipping",
+      label: "NormalShipping",
+      amount: {
+        currency: "USD",
+        value: "10.00",
+      },
+      selected: false,
+    },
+    {
+      id: "FastShipping",
+      label: "FastShipping",
+      amount: {
+        currency: "USD",
+        value: "5.00",
+      },
+      selected: false,
+    },
+  ],
+};
+
+const defaultOptions = {
+  requestPayerName: true,
+  requestPayerEmail: false,
+  reqeustPayerPhone: false,
+  requestShipping: true,
+  shippingType: "shipping"
+};
rename from dom/payments/test/Bug1443914ChromeScript.js
rename to dom/payments/test/ShippingOptionsChromeScript.js
--- a/dom/payments/test/Bug1443914ChromeScript.js
+++ b/dom/payments/test/ShippingOptionsChromeScript.js
@@ -9,72 +9,84 @@ const paymentSrv = Cc["@mozilla.org/dom/
 
 function emitTestFail(message) {
   sendAsyncMessage("test-fail", message);
 }
 function emitTestPass(message) {
   sendAsyncMessage("test-pass", message);
 }
 
-const shippingAddress = Cc["@mozilla.org/dom/payments/payment-address;1"].
-                           createInstance(Ci.nsIPaymentAddress);
-const addressLine = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
-const address = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
-address.data = "Easton Ave";
-addressLine.appendElement(address);
-shippingAddress.init("USA",              // country
-                     addressLine,        // address line
-                     "CA",               // region
-                     "San Bruno",        // city
-                     "Test locality",    // dependent locality
-                     "94066",            // postal code
-                     "123456",           // sorting code
-                     "en",               // language code
-                     "Testing Org",      // organization
-                     "Bill A. Pacheco",  // recipient
-                     "+1-434-441-3879"); // phone
+let expectedRequestOption = null;
+let expectedUpdatedOption = null;
+let changeShippingOption = null;
+
+function showResponse(requestId) {
+  const showResponseData = Cc["@mozilla.org/dom/payments/general-response-data;1"].
+                              createInstance(Ci.nsIGeneralResponseData);
+  showResponseData.initData({});
+  const showResponse = Cc["@mozilla.org/dom/payments/payment-show-action-response;1"].
+                          createInstance(Ci.nsIPaymentShowActionResponse);
+  showResponse.init(requestId,
+                    Ci.nsIPaymentActionResponse.PAYMENT_ACCEPTED,
+                    "testing-payment-method",   // payment method
+                    showResponseData,           // payment method data
+                    "Bill A. Pacheco",          // payer name
+                    "",                         // payer email
+                    "");                        // payer phone
+  paymentSrv.respondPayment(showResponse.QueryInterface(Ci.nsIPaymentActionResponse));
+}
+
+function showRequest(requestId) {
+  let request = paymentSrv.getPaymentRequestById(requestId);
+  const message = "request.shippingOption should be " + expectedRequestOption +
+                  " when calling show(), but got " + request.shippingOption + ".";
+  if (request.shippingOption != expectedRequestOption) {
+    emitTestFail(message);
+  } else {
+    emitTestPass(message);
+  }
+  if (changeShippingOption) {
+    paymentSrv.changeShippingOption(requestId, changeShippingOption);
+  } else {
+    showResponse(requestId);
+  }
+}
+
+function updateRequest(requestId) {
+  let request = paymentSrv.getPaymentRequestById(requestId);
+  const message = "request.shippingOption should be " + expectedUpdatedOption +
+                  " when calling updateWith(), but got " + request.shippingOption + ".";
+  if (request.shippingOption != expectedUpdatedOption) {
+    emitTestFail(message);
+  } else {
+    emitTestPass(message);
+  }
+  showResponse(requestId);
+}
 
 const TestingUIService = {
-  showPayment: function(requestId) {
-    paymentSrv.changeShippingAddress(requestId, shippingAddress);
-  },
+  showPayment: showRequest,
   abortPayment: function(requestId) {
   },
   completePayment: function(requestId) {
     let request = paymentSrv.getPaymentRequestById(requestId);
     let completeResponse = Cc["@mozilla.org/dom/payments/payment-complete-action-response;1"].
                            createInstance(Ci.nsIPaymentCompleteActionResponse);
     completeResponse.init(requestId, Ci.nsIPaymentActionResponse.COMPLETE_SUCCEEDED);
     paymentSrv.respondPayment(completeResponse.QueryInterface(Ci.nsIPaymentActionResponse));
   },
-  updatePayment: function(requestId) {
-    let request = paymentSrv.getPaymentRequestById(requestId);
-    if (request.shippingOptions != null) {
-      emitTestFail("request.shippingOptions should be null");
-    } else {
-      emitTestPass("request.shippingOptions should be null");
-    }
-    const showResponseData = Cc["@mozilla.org/dom/payments/general-response-data;1"].
-                                createInstance(Ci.nsIGeneralResponseData);
-    showResponseData.initData({});
-    const showResponse = Cc["@mozilla.org/dom/payments/payment-show-action-response;1"].
-                            createInstance(Ci.nsIPaymentShowActionResponse);
-    showResponse.init(requestId,
-                      Ci.nsIPaymentActionResponse.PAYMENT_ACCEPTED,
-                      "testing-payment-method",   // payment method
-                      showResponseData,           // payment method data
-                      "Bill A. Pacheco",          // payer name
-                      "",                         // payer email
-                      "");                        // payer phone
-    paymentSrv.respondPayment(showResponse.QueryInterface(Ci.nsIPaymentActionResponse));
-  },
+  updatePayment: updateRequest,
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIPaymentUIService]),
 };
 
-addMessageListener("set-checking-shipping-options-ui-service", function() {
-  paymentSrv.setTestingUIService(TestingUIService.QueryInterface(Ci.nsIPaymentUIService));
+paymentSrv.setTestingUIService(TestingUIService.QueryInterface(Ci.nsIPaymentUIService));
+
+addMessageListener("set-expected-results", function(results) {
+  expectedRequestOption = results.requestResult;
+  expectedUpdatedOption = results.responseResult;
+  changeShippingOption = results.changeOptionResult;
 });
 
 addMessageListener("teardown", function() {
   paymentSrv.cleanup();
   paymentSrv.setTestingUIService(null);
   sendAsyncMessage('teardown-complete');
 });
--- a/dom/payments/test/mochitest.ini
+++ b/dom/payments/test/mochitest.ini
@@ -1,30 +1,31 @@
 [DEFAULT]
 # skip-if !e10s will be removed once non-e10s is supported
 skip-if = !e10s
 scheme = https
 support-files =
   simple_payment_request.html
   echo_payment_request.html
   BasiccardChromeScript.js
-  Bug1443914ChromeScript.js
   ConstructorChromeScript.js
   CurrencyAmountValidationChromeScript.js
+  DefaultData.js
   GeneralChromeScript.js
   PMIValidationChromeScript.js
+  ShippingOptionsChromeScript.js
   ShowPaymentChromeScript.js
   RequestShippingChromeScript.js
 
 [test_abortPayment.html]
 run-if = nightly_build # Bug 1390018: Depends on the Nightly-only UI service
 [test_basiccard.html]
 [test_block_none10s.html]
 skip-if = e10s # Bug 1408250: Don't expose PaymentRequest Constructor in non-e10s
-[test_bug1443914.html]
 [test_canMakePayment.html]
 run-if = nightly_build # Bug 1390737: Depends on the Nightly-only UI service
 [test_constructor.html]
 [test_currency_amount_validation.html]
 [test_payment-request-in-iframe.html]
 [test_pmi_validation.html]
 [test_requestShipping.html]
+[test_shippingOptions.html]
 [test_showPayment.html]
rename from dom/payments/test/test_bug1443914.html
rename to dom/payments/test/test_shippingOptions.html
--- a/dom/payments/test/test_bug1443914.html
+++ b/dom/payments/test/test_shippingOptions.html
@@ -1,127 +1,194 @@
 <!DOCTYPE HTML>
 <html>
 <!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1440041
 https://bugzilla.mozilla.org/show_bug.cgi?id=1443914
 -->
 <head>
   <meta charset="utf-8">
-  <title>Test for Bug 1443914</title>
+  <title>Test for shippingOptions related bugs</title>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="./DefaultData.js"></script>
   <script type="application/javascript">
 
   "use strict";
   SimpleTest.waitForExplicitFinish();
 
-  var gUrl = SimpleTest.getTestFileURL('Bug1443914ChromeScript.js');
+  var gUrl = SimpleTest.getTestFileURL('ShippingOptionsChromeScript.js');
   var gScript = SpecialPowers.loadChromeScript(gUrl);
 
   function testFailHandler(message) {
     ok(false, message);
   }
   function testPassHandler(message) {
     ok(true, message);
   }
   gScript.addMessageListener("test-fail", testFailHandler);
   gScript.addMessageListener("test-pass", testPassHandler);
 
-  // testing data declation
-  const defaultMethods = [{
-    supportedMethods: "basic-card",
-    data: {
-      supportedNetworks: ['unionpay', 'visa', 'mastercard', 'amex', 'discover',
-                          'diners', 'jcb', 'mir',
-      ],
-      supportedTypes: ['prepaid', 'debit', 'credit'],
+  let shippingOptions = [{
+    id: "NormalShipping",
+    label: "NormalShipping",
+    amount: {
+      currency: "USD",
+      value: "10.00",
     },
-  }, {
-    supportedMethods: "testing-payment-method",
-  }];
-
-  const defaultDetails = {
-    id: "test payment",
-    total: {
-      label: "Total",
-      amount: {
-        currency: "USD",
-        value: "1.00"
-      }
+    selected: true,
+  },{
+    id: "FastShipping",
+    label: "FastShipping",
+    amount: {
+      currency: "USD",
+      value: "5.00",
     },
-    shippingOptions: [
-      {
-        id: "NormalShipping",
-        label: "NormalShipping",
-        amount: {
-          currency: "USD",
-          value: "10.00"
-        },
-        selected: false,
-      },
-    ],
-  };
-
-  const defaultOptions = {
-    requestPayerName: true,
-    requestPayerEmail: false,
-    reqeustPayerPhone: false,
-    requestShipping: true,
-    shippingType: "shipping"
-  };
+    selected: false,
+  }]
 
-  const updateDetails = {
-    total: {
-      label: "Total",
-      amount: {
-        currency: "USD",
-        value: "1.00"
+  // testing function main body
+  function testShippingOptionsTemplate(initDetails,
+				       optionUpdateDetails,
+                                       expectedRequestOption,
+				       expectedOptionChangeOption,
+				       expectedResponseOption) {
+    const expectedResults = {requestResult: expectedRequestOption,
+                             changeOptionResult: expectedOptionChangeOption,
+                             responseResult: expectedResponseOption,};
+    gScript.sendAsyncMessage("set-expected-results", expectedResults);
+    return new Promise((resolve, reject) => {
+      const request = new PaymentRequest(defaultMethods, initDetails, defaultOptions);
+      const handler = SpecialPowers.getDOMWindowUtils(window).setHandlingUserInput(true);
+      is(request.shippingOption, expectedRequestOption,
+         "request.shippingOption should be " + expectedRequestOption +
+	 " after created, but got " + request.shippingOption + ".");
+      if (optionUpdateDetails) {
+	request.addEventListener("shippingoptionchange", event => {
+	  is(request.shippingOption, expectedOptionChangeOption,
+             "request.shippingOption should be " + expectedOptionChangeOption +
+	     " in shippingoptionchange event, but got " + request.shippingOption + ".");
+          event.updateWith(optionUpdateDetails);
+	});
       }
-    },
-    error: "",
-  };
-  // testing function main body
-  function test_bug1443914() {
-    gScript.sendAsyncMessage("set-checking-shipping-options-ui-service");
-    return new Promise((resolve, reject) => {
-      const request = new PaymentRequest(defaultMethods, defaultDetails, defaultOptions);
-      const handler = SpecialPowers.getDOMWindowUtils(window).setHandlingUserInput(true);
-      request.addEventListener("shippingaddresschange", (event) => {
-        event.updateWith(updateDetails);
-      });
-      request.addEventListener("shippingoptionchange", (event) => {
-        event.updateWith(updateDetails);
-      });
       request.show().then(response => {
-        response.complete("success").then(() => {
+        is(response.shippingOption, expectedResponseOption,
+	"response.shippingOption should be " + expectedResponseOption +
+	 ", but got " + response.shippingOption + ".");
+	response.complete("success").then(() => {
 	  resolve();
 	}).catch(error => {
 	  ok(false, "Unexpected error: " + error.name);
 	  resolve();
-	});
+	})
+      }, response => {
       }).catch(error => {
         ok(false, "Unexpected error: " + error.name);
 	resolve();
       }).finally(handler.destruct);
     });
   }
 
+  // test no selected shipping option in default
+  function testNoSelectedShippingOptions() {
+    return testShippingOptionsTemplate(defaultDetails,   // initial details
+				       null,             // update details for optionchange
+				       null,             // expected request.shippintOption after create
+				       null,             // expected request.shippingOption after optionchange
+				       null);            // expected response.shippingOption
+  }
+
+  // test select one shipping option in default
+  function testSelectedOneShippingOption() {
+    let details = Object.assign({}, defaultDetails);
+    details.shippingOptions = shippingOptions;
+    details.shippingOptions[0].selected = true;
+    details.shippingOptions[1].selected = false;
+    const expectedOption = details.shippingOptions[0].id;
+    return testShippingOptionsTemplate(details,          // initial details
+				       null,             // update details for optionchange
+				       expectedOption,   // expected request.shippintOption after create
+				       null,             // expected request.shippingOption after optionchange
+				       expectedOption);  // expected response.shippingOption
+  }
+
+  // test select multiple shipping options in default
+  function testMultiSelectedShippingOptions() {
+    let details = Object.assign({}, defaultDetails);
+    details.shippingOptions = shippingOptions;
+    details.shippingOptions[0].selected = true;
+    details.shippingOptions[1].selected = true;
+    const expectedOption = details.shippingOptions[1].id;
+    return testShippingOptionsTemplate(details,          // initial details
+				       null,             // update details for optionchange
+				       expectedOption,   // expected request.shippintOption after create
+				       null,             // expected request.shippingOption after optionchange
+				       expectedOption);  // expected response.shippingOption
+  }
+
+  // test no selected shipping option in default, but selected by user
+  function testSelectedByUser() {
+    let updateDetails = Object.assign({}, defaultDetails);
+    updateDetails.shippingOptions = shippingOptions;
+    updateDetails.shippingOptions[0].selected = true;
+    updateDetails.shippingOptions[1].selected = false;
+    const expectedOption = updateDetails.shippingOptions[0].id;
+    return testShippingOptionsTemplate(defaultDetails,   // initial details
+				       updateDetails,    // update details for optionchange
+				       null,             // expected request.shippintOption after create
+				       expectedOption,   // expected request.shippingOption after optionchange
+				       expectedOption);  // expected response.shippingOption
+  }
+
+  // test no selected shipping option in default, but selected by user then updated
+  // by merchant to the other.
+  function testUpdateSelectedByMerchant() {
+    let updateDetails = Object.assign({}, defaultDetails);
+    updateDetails.shippingOptions = shippingOptions;
+    updateDetails.shippingOptions[0].selected = false;
+    updateDetails.shippingOptions[1].selected = true;
+    const expectedOption = updateDetails.shippingOptions[0].id;
+    const expectedResponse = updateDetails.shippingOptions[1].id;
+    return testShippingOptionsTemplate(defaultDetails,   // initial details
+				       updateDetails,    // update details for optionchange
+				       null,             // expected request.shippintOption after create
+				       expectedOption,   // expected request.shippingOption after optionchange
+				       expectedResponse);// expected response.shippingOption
+  }
+
+  // test update shipping options to null
+  function testUpdateShippingOptionsToNull() {
+    let updateDetails = Object.assign({}, defaultDetails);
+    delete updateDetails.shippingOptions;
+    const expectedOption = defaultDetails.shippingOptions[0].id;
+    return testShippingOptionsTemplate(defaultDetails,   // initial details
+				       updateDetails,    // update details for optionchange
+				       null,             // expected request.shippintOption after create
+				       expectedOption,   // expected request.shippingOption after optionchange
+				       null);            // expected response.shippingOption
+  }
+
   function teardown() {
     gScript.addMessageListener("teardown-complete", function teardownCompleteHandler() {
       gScript.removeMessageListener("teardown-complete", teardownCompleteHandler);
       gScript.removeMessageListener("test-fail", testFailHandler);
       gScript.removeMessageListener("test-pass", testPassHandler);
       gScript.destroy();
       SimpleTest.finish();
     });
     gScript.sendAsyncMessage("teardown");
   }
 
   function runTests() {
-    test_bug1443914()
+    testNoSelectedShippingOptions()
+    .then(testSelectedOneShippingOption)
+    .then(testMultiSelectedShippingOptions)
+    .then(testSelectedByUser)
+    .then(testUpdateSelectedByMerchant)
+    .then(testUpdateShippingOptionsToNull)
     .then(teardown)
     .catch( e => {
       ok(false, "Unexpected error: " + e.name);
       SimpleTest.finish();
     });
   }
 
   window.addEventListener('load', function() {
@@ -130,11 +197,12 @@ https://bugzilla.mozilla.org/show_bug.cg
         ['dom.payments.request.enabled', true],
       ]
     }, runTests);
   });
 
   </script>
 </head>
 <body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1440041">Mozilla Bug 1440041</a>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1443914">Mozilla Bug 1443914</a>
 </body>
 </html>