common.spec.js 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
/*jshint node: true, jasmine: true, browser: true */
/*global ContactFindOptions, ContactName, Q*/

/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

// these tests are meant to be executed by Cordova Medic Appium runner
// you can find it here: https://github.com/apache/cordova-medic/
// it is not necessary to do a full CI setup to run these tests, just run:
// node cordova-medic/medic/medic.js appium --platform android --plugins cordova-plugin-contacts

'use strict';

var wdHelper = global.WD_HELPER;
var screenshotHelper = global.SCREENSHOT_HELPER;
var contactsHelper = require('../helpers/contactsHelper');

var MINUTE = 60 * 1000;
var PLATFORM = global.PLATFORM;
var UNORM = global.UNORM;

describe('Contacts UI Automation Tests', function () {
    var driver;
    var webviewContext;
    var promiseCount = 0;
    // going to set this to false if session is created successfully
    var failedToStart = true;

    function getNextPromiseId() {
        return 'appium_promise_' + promiseCount++;
    }

    function saveScreenshotAndFail(error) {
        fail(error);
        return screenshotHelper
            .saveScreenshot(driver)
            .quit()
            .then(function () {
                return getDriver();
            });
    }

    function getDriver() {
        driver = wdHelper.getDriver(PLATFORM);
        return wdHelper.getWebviewContext(driver, 2)
            .then(function (context) {
                webviewContext = context;
                return driver.context(webviewContext);
            })
            .then(function () {
                return wdHelper.waitForDeviceReady(driver);
            })
            .then(function () {
                return wdHelper.injectLibraries(driver);
            });
    }

    function addContact(firstName, lastName, bday) {
        var bdayString = bday ? bday.toDateString() : undefined;
        var contactName = contactsHelper.getContactName(firstName, lastName);
        return driver
            .context(webviewContext)
            .setAsyncScriptTimeout(MINUTE)
            .executeAsync(function (contactname, bday, callback) {
                navigator.contacts.create({
                    'displayName': contactname.formatted,
                    'name': contactname,
                    'note': 'DeleteMe',
                    'birthday': new Date(bday)
                }).save(function (successResult) {
                    callback(successResult);
                }, function (failureResult) {
                    callback(failureResult);
                });
            }, [contactName, bdayString])
            .then(function (result) {
                if (result && result.hasOwnProperty('code')) {
                    throw result;
                }
                return result;
            });
    }

    function pickContact(name) {
        var promiseId = getNextPromiseId();
        return driver
            .context(webviewContext)
            .execute(function (pID) {
                navigator._appiumPromises[pID] = Q.defer();
                navigator.contacts.pickContact(function (contact) {
                    navigator._appiumPromises[pID].resolve(contact);
                }, function (err) {
                    navigator._appiumPromises[pID].reject(err);
                });
            }, [promiseId])
            .context('NATIVE_APP')
            .then(function () {
                switch (PLATFORM) {
                    case 'ios':
                        return driver
                            .waitForElementByAccessibilityId(name, 20000)
                            .elementByAccessibilityId(name);
                    case 'android':
                        return driver
                            .waitForElementByXPath('//android.widget.TextView[@text="' + name + '"]', MINUTE);
                }
            })
            .click()
            .context(webviewContext)
            .executeAsync(function (pID, cb) {
                navigator._appiumPromises[pID].promise
                .then(function (contact) {
                    // for some reason Appium cannot get Date object
                    // let's make birthday a string then
                    contact.birthday = contact.birthday.toDateString();
                    cb(contact);
                }, function (err) {
                    cb('ERROR: ' + err);
                });
            }, [promiseId])
            .then(function (result) {
                if (typeof result === 'string' && result.indexOf('ERROR:') === 0) {
                    throw result;
                }
                return result;
            });
    }

    function renameContact(oldName, newGivenName, newFamilyName) {
        return driver
            .context(webviewContext)
            .setAsyncScriptTimeout(7 * MINUTE)
            .executeAsync(function (oldname, newgivenname, newfamilyname, callback) {
                var obj = new ContactFindOptions();
                obj.filter = oldname;
                obj.multiple = false;

                navigator.contacts.find(['displayName', 'name'], function (contacts) {
                    if (contacts.length === 0) {
                        callback({ 'code': -35142 });
                        return;
                    }
                    var contact = contacts[0];
                    contact.displayName = newgivenname + ' ' + newfamilyname;
                    var name = new ContactName();
                    name.givenName = newgivenname;
                    name.familyName = newfamilyname;
                    contact.name = name;
                    contact.save(callback, callback);
                }, function (result) {
                    callback(result);
                }, obj);
            }, [oldName, newGivenName, newFamilyName])
            .then(function (result) {
                if (result && result.hasOwnProperty('code')) {
                    if (result.code === -35142) {
                        throw 'Couldn\'t find the contact "' + oldName + '"';
                    }
                    throw result;
                }
                return result;
            });
    }

    function removeTestContacts() {
        return driver
            .context(webviewContext)
            .setAsyncScriptTimeout(MINUTE)
            .executeAsync(function (callback) {
                var obj = new ContactFindOptions();
                obj.filter = 'DeleteMe';
                obj.multiple = true;
                navigator.contacts.find(['note'], function (contacts) {
                    var removes = [];
                    contacts.forEach(function (contact) {
                        removes.push(contact);
                    });
                    if (removes.length === 0) {
                        return;
                    }

                   var nextToRemove;
                   if (removes.length > 0) {
                        nextToRemove = removes.shift();
                    }

                    function removeNext(item) {
                        if (typeof item === 'undefined') {
                            callback();
                            return;
                        }

                        if (removes.length > 0) {
                            nextToRemove = removes.shift();
                        } else {
                            nextToRemove = undefined;
                        }

                        item.remove(function removeSucceeded() {
                            removeNext(nextToRemove);
                        }, function removeFailed() {
                            removeNext(nextToRemove);
                        });
                    }
                    removeNext(nextToRemove);
                }, function (failureResult) {
                    callback(failureResult);
                }, obj);
            }, [])
            .then(function (result) {
                if (typeof result !== 'undefined') {
                    throw result;
                }
            });
    }

    function checkSession(done) {
        if (failedToStart) {
            fail('Failed to start a session');
            done();
        }
    }

    afterAll(function (done) {
        checkSession(done);
        driver
            .quit()
            .done(done);
    }, MINUTE);

    it('should connect to an appium endpoint properly', function (done) {
        getDriver()
            .then(function () {
                failedToStart = false;
            }, fail)
            .then(function () {
                // on iOS and Android >= 6, first interaction with contacts API will trigger the permission dialog.
                // We will attempt to bust it manually here, by triggering the contacts API
                // and waiting for the native dialog to show up, then dismissing the alert.
                // This only needs to be done once.
                // NOTE: in earlier versions of iOS (9.3 and below), using the older UI testing library
                // (UIAutomation), Appium's autoAcceptAlerts capability handles this for us. This logic
                // is here as a transition between UIAutomation and XCUITest and is compatible with both.
                // More details in the comment below.
                var promiseId = getNextPromiseId();
                var contactName = contactsHelper.getContactName('Permission', 'Buster');
                return driver
                    .context(webviewContext)
                    .execute(function (pID, contactname) {
                        navigator._appiumPromises[pID] = Q.defer();
                        navigator.contacts.create({
                            'displayName': contactname.formatted,
                            'name': contactname,
                            'note': 'DeleteMe'
                        }).save(function (contact) {
                            navigator._appiumPromises[pID].resolve(contact);
                        }, function (err) {
                            navigator._appiumPromises[pID].reject(err);
                        });
                    }, [promiseId, contactName])
                    .context('NATIVE_APP')
                    .then(function () {
                        // iOS
                        if (PLATFORM === 'ios') {
                            return driver.acceptAlert()
                                .then(function alertDismissed() {
                                    // TODO: once we move to only XCUITest-based (which is force on you in either iOS 10+ or Xcode 8+)
                                    // UI tests, we will have to:
                                    // a) remove use of autoAcceptAlerts appium capability since it no longer functions in XCUITest
                                    // b) can remove this entire then() clause, as we do not need to explicitly handle the acceptAlert
                                    //    failure callback, since we will be guaranteed to hit the permission dialog on startup.
                                 }, function noAlert() {
                                     // in case the contacts permission alert never showed up: no problem, don't freak out.
                                     // This can happen if:
                                     // a) The applications-under-test already had contacts permissions granted to it
                                     // b) Appium's autoAcceptAlerts capability is provided (and functioning)
                                 });
                        }

                        // Android
                        return driver
                            .elementByXPath('//android.widget.Button[translate(@text, "alow", "ALOW")="ALLOW"]')
                            .click()
                            .fail(function noAlert() { });
                    })
                    .context(webviewContext)
                    .executeAsync(function (pID, cb) {
                        navigator._appiumPromises[pID].promise
                            .then(function (result) {
                                cb(result);
                            }, function (err) {
                                cb('ERROR: ' + err);
                            });
                    }, [promiseId])
                    .then(function (result) {
                        if (typeof result === 'string' && result.indexOf('ERROR:') === 0) {
                            throw result;
                        }
                        return result;
                    });
            })
            .done(done);
    }, 10 * MINUTE);

    describe('Picking contacts', function () {
        afterEach(function (done) {
            checkSession(done);
            removeTestContacts()
                .finally(done);
        }, MINUTE);

        it('contacts.ui.spec.1 Pick a contact', function (done) {
            checkSession(done);
            var bday = new Date(1991, 1, 1);
            driver
                .then(function () {
                    return addContact('Test', 'Contact', bday);
                })
                .then(function () {
                    return pickContact('Test Contact');
                })
                .then(function (contact) {
                    expect(contact.name.givenName).toBe('Test');
                    expect(contact.name.familyName).toBe('Contact');
                    expect(contact.birthday).toBe(bday.toDateString());
                })
                .fail(saveScreenshotAndFail)
                .done(done);
        }, 5 * MINUTE);

        it('contacts.ui.spec.2 Update an existing contact', function (done) {
            checkSession(done);
            driver
                .then(function () {
                    return addContact('Dooney', 'Evans');
                })
                .then(function () {
                    return renameContact('Dooney Evans', 'Urist', 'McContact');
                })
                .then(function () {
                    return pickContact('Urist McContact');
                })
                .then(function (contact) {
                    expect(contact.name.givenName).toBe('Urist');
                    expect(contact.name.familyName).toBe('McContact');
                })
                .fail(saveScreenshotAndFail)
                .done(done);
        }, 10 * MINUTE);

        it('contacts.ui.spec.3 Create a contact with no name', function (done) {
            checkSession(done);
            driver
                .then(function () {
                    return addContact();
                })
                .then(function () {
                    switch (PLATFORM) {
                        case 'android':
                            return pickContact('(No name)');
                        case 'ios':
                            return pickContact('No Name');
                    }
                })
                .then(function (contact) {
                    if (contact.name) {
                        expect(contact.name.givenName).toBeFalsy();
                        expect(contact.name.middleName).toBeFalsy();
                        expect(contact.name.familyName).toBeFalsy();
                        expect(contact.name.formatted).toBeFalsy();
                    } else {
                        expect(contact.name).toBeFalsy();
                    }
                })
                .fail(saveScreenshotAndFail)
                .done(done);
        }, 5 * MINUTE);

        it('contacts.ui.spec.4 Create a contact with Unicode characters in name', function (done) {
            checkSession(done);
            driver
                .then(function () {
                    return addContact('Н€йромонах', 'ФеофаЊ');
                })
                .then(function () {
                    return pickContact('Н€йромонах ФеофаЊ');
                })
                .then(function (contact) {
                    expect(contact.name.givenName).toBe('Н€йромонах');
                    expect(contact.name.familyName).toBe('ФеофаЊ');
                })
                .fail(saveScreenshotAndFail)
                .done(done);
        }, 5 * MINUTE);
    });
});