Esempio n. 1
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create our test contacts.
        self.contact_list = [MockContact(tel={'type': 'Mobile', 'value': "{}".format(i) * 9}) for i in range(3)]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("999999999")

        # Verify that there are no results.
        self.UTILS.element.waitForElements(DOM.Contacts.search_no_contacts_found, "'No contacts found' message")
Esempio n. 2
0
class test_main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)
        self.contact = MockContact(tel=[{'type': 'Mobile', 'value': '111111111'},
                                        {'type': 'Mobile', 'value': '222222222'}])

        self.UTILS.general.insertContact(self.contact)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.messages.launch()

        # Type a message containing the required string
        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test message")

        # Search for our contact.
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)
        self.contacts.search(self.contact['name'])
        self.contacts.select_search_result_several_phones(self.contact['name'],
                                                          self.contact['tel'][0]['value'], cancel=True)
Esempio n. 3
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.test_contacts = [MockContact() for i in range(2)]
        map(self.UTILS.general.insertContact, self.test_contacts)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("XXXX")

        # Verify our contact is listed.
        self.contacts.check_search_results(self.test_contacts[0]["givenName"], False)

        # Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.test_contacts[1]["givenName"], False)
Esempio n. 4
0
class test_main(GaiaTestCase):
    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create test contacts.
        self.contact_list = [MockContact() for i in range(3)]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for the sought contact.
        self.UTILS.reporting.logResult(
            "info", "<b>Search against number in 'given name' field ...</b>")
        self.contacts.search(self.contact_list[1]["tel"]["value"])
        self.contacts.check_search_results(self.contact_list[1]["givenName"])
Esempio n. 5
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create test contacts.
        self.contact_list = [MockContact() for i in range(3)]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for the sought contact.
        self.UTILS.reporting.logResult("info", "<b>Search against number in 'given name' field ...</b>")
        self.contacts.search(self.contact_list[1]["tel"]["value"])
        self.contacts.check_search_results(self.contact_list[1]["givenName"])
Esempio n. 6
0
class test_main(GaiaTestCase):
    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create our test contacts.
        self.contact_list = [
            MockContact(tel={
                'type': 'Mobile',
                'value': "{}".format(i) * 9
            }) for i in range(3)
        ]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("999999999")

        # Verify that there are no results.
        self.UTILS.element.waitForElements(
            DOM.Contacts.search_no_contacts_found,
            "'No contacts found' message")
Esempio n. 7
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create our test contacts.
        self.contact_list = [MockContact() for i in range(3)]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search(self.contact_list[0]["tel"]["value"])

        # Verify that we're now in the 'search results' screen.
        self.UTILS.element.waitForElements(DOM.Contacts.search_results_list, "Search results list")

        # Cancel the search.
        x = self.UTILS.element.getElement(DOM.Contacts.search_cancel_btn, "Cancel search button")
        x.tap()

        # Verify that we're no longer in the 'search results' screen.
        self.UTILS.element.waitForNotElements(DOM.Contacts.search_results_list, "Search results list")
Esempio n. 8
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create test contacts.
        self.contact = MockContact()
        self.UTILS.general.insertContact(self.contact)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Select a contact.
        self.contacts.search(self.contact["givenName"])
        self.contacts.select_search_result(self.contact["givenName"])

        # Tap on edit mode.
        editBTN = self.UTILS.element.getElement(DOM.Contacts.edit_details_button, "Edit details button")
        editBTN.tap()
        self.UTILS.element.waitForElements(DOM.Contacts.edit_contact_header, "'Edit contacts' screen header")
Esempio n. 9
0
class test_main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)

        self.phone_number = self.UTILS.general.get_config_variable("phone_number", "custom")
        self.contact = MockContact(tel={'type': '', 'value': self.phone_number})

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.reporting.logComment("Using target telephone number " + self.contact["tel"]["value"])

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.messages.launch()

        # Type a message containing the required string
        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test message")

        # Search for our contact.
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)
        self.contacts.search("Knot A Match")
        self.contacts.check_search_results("Knot A Match", False)
Esempio n. 10
0
class test_main(GaiaTestCase):
    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)

        self.phone_number = self.UTILS.general.get_config_variable(
            "phone_number", "custom")
        self.contact = MockContact(tel={
            'type': '',
            'value': self.phone_number
        })

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.reporting.logComment("Using target telephone number " +
                                        self.contact["tel"]["value"])

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.messages.launch()

        # Type a message containing the required string
        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test message")

        # Search for our contact.
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)
        self.contacts.search("Knot A Match")
        self.contacts.check_search_results("Knot A Match", False)
Esempio n. 11
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.test_contacts = [MockContact() for i in range(3)]
        self.test_contacts[0]["givenName"] = "nameJohn"
        self.beginningWord = "name"

        map(self.UTILS.general.insertContact, self.test_contacts)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # With name: Search for the sought contact.
        self.contacts.search(self.beginningWord)

        # With name: Verify our contact is listed.
        self.contacts.check_search_results(self.test_contacts[0]["givenName"])

        # With name: Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.test_contacts[1]["givenName"], False)
        self.contacts.check_search_results(self.test_contacts[2]["givenName"], False)
Esempio n. 12
0
class test_main(GaiaTestCase):
    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.test_contacts = [MockContact() for i in range(2)]
        map(self.UTILS.general.insertContact, self.test_contacts)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("XXXX")

        # Verify our contact is listed.
        self.contacts.check_search_results(self.test_contacts[0]["givenName"],
                                           False)

        # Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.test_contacts[1]["givenName"],
                                           False)
Esempio n. 13
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create our test contacts.
        self.contact = MockContact()
        self.UTILS.general.insertContact(self.contact)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search(self.contact["tel"]["value"])

        # Verify our contact is listed.
        self.contacts.check_search_results(self.contact["givenName"], True)
Esempio n. 14
0
class main(GaiaTestCase):
    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.loop = Loop(self)
        self.contacts = Contacts(self)
        self.settings = Settings(self)
        self.fxa_user = self.UTILS.general.get_config_variable(
            "fxa_user", "common")
        self.fxa_pass = self.UTILS.general.get_config_variable(
            "fxa_pass", "common")

        self.connect_to_network()

        self.target_name = "QA"
        self.test_contacts = [MockContact() for i in range(5)]
        self.test_contacts[0]["givenName"] = self.target_name
        self.test_contacts[0]["familyName"] = "Automation"
        map(self.UTILS.general.insertContact, self.test_contacts)

        # Clean start
        if not self.loop.is_installed():
            self.loop.install()
        else:
            self.loop.launch()
            # If already logged in, logout
            if not self.loop.wizard_or_login():
                self.loop.open_settings()
                self.loop.logout()

        self.settings.launch()
        self.settings.fxa()
        self.settings.fxa_log_out()
        self.apps.kill_all()
        time.sleep(2)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # First, login
        self.loop.launch()
        result = self.loop.wizard_or_login()

        if result:
            self.loop.firefox_login(self.fxa_user, self.fxa_pass)
            self.loop.allow_permission_ffox_login()
            self.UTILS.element.waitForElements(DOM.Loop.app_header,
                                               "Loop main view")

            self.loop.open_address_book()
            self.contacts.search(self.target_name)
            self.contacts.check_search_results(self.target_name)
Esempio n. 15
0
class main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.loop = Loop(self)
        self.contacts = Contacts(self)
        self.settings = Settings(self)
        self.fxa_user = self.UTILS.general.get_config_variable("fxa_user", "common")
        self.fxa_pass = self.UTILS.general.get_config_variable("fxa_pass", "common")

        self.connect_to_network()

        self.target_name = "QA"
        self.test_contacts = [MockContact() for i in range(5)]
        self.test_contacts[0]["givenName"] = self.target_name
        self.test_contacts[0]["familyName"] = "Automation"
        map(self.UTILS.general.insertContact, self.test_contacts)

        # Clean start
        if not self.loop.is_installed():
            self.loop.install()
        else:
            self.loop.launch()
            # If already logged in, logout
            if not self.loop.wizard_or_login():
                self.loop.open_settings()
                self.loop.logout()

        self.settings.launch()
        self.settings.fxa()
        self.settings.fxa_log_out()
        self.apps.kill_all()
        time.sleep(2)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # First, login
        self.loop.launch()
        result = self.loop.wizard_or_login()

        if result:
            self.loop.firefox_login(self.fxa_user, self.fxa_pass)
            self.loop.allow_permission_ffox_login()
            self.UTILS.element.waitForElements(DOM.Loop.app_header, "Loop main view")

            self.loop.open_address_book()   
            self.contacts.search(self.target_name)
            self.contacts.check_search_results(self.target_name)
Esempio n. 16
0
class test_main(GaiaTestCase):
    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)
        self.gallery = Gallery(self)

        self.test_num = self.UTILS.general.get_config_variable(
            "phone_number", "custom")
        self.cont = MockContact(tel={"type": "Mobile", "value": self.test_num})

        self.UTILS.general.insertContact(self.cont)
        self.UTILS.general.add_file_to_device('./tests/_resources/imga.jpg')
        self.UTILS.reporting.logComment("Using target telephone number " +
                                        self.cont["tel"]["value"])

    def tearDown(self):
        self.UTILS.general.remove_files()
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.messages.launch()

        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test")

        self.messages.create_mms_image()
        self.gallery.click_on_thumbnail_at_position_mms(0)

        # Search for our contact.
        time.sleep(5)
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

        self.contacts.search(self.cont["name"])
        self.contacts.check_search_results(self.cont["name"])

        result = self.UTILS.element.getElements(
            DOM.Contacts.search_results_list, "Contacts search results")
        for contact in result:
            if contact.text == self.cont["name"]:
                contact.tap()
                break

        self.apps.switch_to_displayed_app()

        # Now check the correct name is in the 'To' list.
        self.messages.checkIsInToField(self.cont["name"])
        self.messages.sendSMS()
Esempio n. 17
0
class test_main(GaiaTestCase):
    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)

        # Prepare the contact we're going to insert.
        self.phone_number = self.UTILS.general.get_config_variable(
            "phone_number", "custom")
        self.contact = MockContact(tel={
            'type': '',
            'value': self.phone_number
        })

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.reporting.logComment("Using target telephone number " +
                                        self.contact["tel"]["value"])

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # Launch messages app.
        self.messages.launch()

        # Type a message containing the required string
        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test message")

        # Search for our contact.
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)
        self.contacts.search(self.contact["name"])
        self.contacts.check_search_results(self.contact["name"])

        contact_list = self.UTILS.element.getElements(
            DOM.Contacts.search_results_list, "Contacts search results")
        for c in contact_list:
            if c.text == self.contact["name"]:
                c.tap()
                break

        # Switch back to the sms iframe.
        self.apps.switch_to_displayed_app()

        # Now check the correct name is in the 'To' list.
        self.messages.checkIsInToField(self.contact["name"])
        self.messages.sendSMS()
Esempio n. 18
0
class test_main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)
        self.gallery = Gallery(self)

        self.test_num = self.UTILS.general.get_config_variable("phone_number", "custom")
        self.cont = MockContact(tel={"type": "Mobile", "value": self.test_num})

        self.UTILS.general.insertContact(self.cont)
        self.UTILS.general.add_file_to_device('./tests/_resources/imga.jpg')
        self.UTILS.reporting.logComment("Using target telephone number " + self.cont["tel"]["value"])

    def tearDown(self):
        self.UTILS.general.remove_files()
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.messages.launch()

        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test")

        self.messages.create_mms_image()
        self.gallery.click_on_thumbnail_at_position_mms(0)

        # Search for our contact.
        time.sleep(5)
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

        self.contacts.search(self.cont["name"])
        self.contacts.check_search_results(self.cont["name"])

        result = self.UTILS.element.getElements(DOM.Contacts.search_results_list, "Contacts search results")
        for contact in result:
            if contact.text == self.cont["name"]:
                contact.tap()
                break

        self.apps.switch_to_displayed_app()

        # Now check the correct name is in the 'To' list.
        self.messages.checkIsInToField(self.cont["name"])
        self.messages.sendSMS()
Esempio n. 19
0
class test_main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.messages = Messages(self)
        self.contacts = Contacts(self)

        # Prepare the contact we're going to insert.
        self.phone_number = self.UTILS.general.get_config_variable("phone_number", "custom")
        self.contact = MockContact(tel={'type': '', 'value': self.phone_number})

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.reporting.logComment("Using target telephone number " + self.contact["tel"]["value"])

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # Launch messages app.
        self.messages.launch()

        # Type a message containing the required string
        self.messages.startNewSMS()
        self.messages.enterSMSMsg("Test message")

        # Search for our contact.
        self.messages.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)
        self.contacts.search(self.contact["name"])
        self.contacts.check_search_results(self.contact["name"])

        contact_list = self.UTILS.element.getElements(DOM.Contacts.search_results_list, "Contacts search results")
        for c in contact_list:
            if c.text == self.contact["name"]:
                c.tap()
                break

        # Switch back to the sms iframe.
        self.apps.switch_to_displayed_app()

        # Now check the correct name is in the 'To' list.
        self.messages.checkIsInToField(self.contact["name"])
        self.messages.sendSMS()
Esempio n. 20
0
class test_main(GaiaTestCase):
    def __init__(self, *args, **kwargs):
        kwargs['restart'] = True
        super(test_main, self).__init__(*args, **kwargs)

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        self.phones = ["177111111", "177222222", "133333333"]
        self.given_names = ["Contact"] * len(self.phones)
        self.family_names = map(str, range(1, len(self.phones) + 1))

        self.test_contacts = [
            MockContact(tel={
                'type': 'Mobile',
                'value': self.phones[i]
            },
                        givenName=self.given_names[i],
                        familyName=self.family_names[i],
                        name="{} {}".format(self.given_names[i],
                                            self.family_names[i]))
            for i in range(len(self.phones))
        ]
        map(self.UTILS.general.insertContact, self.test_contacts)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("77")

        # Verify our contact is listed.
        conditions = [True, True, False]
        names = [c["familyName"] for c in self.test_contacts]
        map(self.contacts.check_search_results, names, conditions)
Esempio n. 21
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)
        self.settings = Settings(self)

        # Create test contacts.
        self.test_contacts = [MockContact() for i in range(2)]
        map(self.UTILS.general.insertContact, self.test_contacts)
        self.new_given_name = "aaaaabbbbbccccaaaa"

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Set up to use data connection.
        self.connect_to_network()

        # Launch contacts app.
        self.contacts.launch()

        # Change the name to "aaaaabbbbbccccaaaa"
        self.contacts.change_contact(self.test_contacts[0]['name'], "givenName",
                                    self.new_given_name)

        # Search for our new contact.
        self.contacts.search("aaa")

        # Verify our contact is listed.
        self.contacts.check_search_results(self.new_given_name, True)

        # Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.test_contacts[1]["givenName"], False)
Esempio n. 22
0
class test_main(GaiaTestCase):

    def __init__(self, *args, **kwargs):
        kwargs['restart'] = True
        super(test_main, self).__init__(*args, **kwargs)

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        self.phones = ["177111111", "177222222", "133333333"]
        self.given_names = ["Contact"] * len(self.phones)
        self.family_names = map(str, range(1, len(self.phones) + 1))

        self.test_contacts = [MockContact(tel={'type': 'Mobile', 'value': self.phones[i]},
                                          givenName=self.given_names[i],
                                          familyName=self.family_names[i],
                                          name="{} {}".format(self.given_names[i], self.family_names[i]))
                              for i in range(len(self.phones))]
        map(self.UTILS.general.insertContact, self.test_contacts)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search("77")

        # Verify our contact is listed.
        conditions = [True, True, False]
        names = [c["familyName"] for c in self.test_contacts]
        map(self.contacts.check_search_results, names, conditions)
Esempio n. 23
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.contact = MockContact(givenName='1111111')
        self.contact2 = MockContact(familyName='2222222')

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.general.insertContact(self.contact2)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.UTILS.reporting.logResult("info", "<b>Search against number in 'given name' field ...</b>")
        self.contacts.search('1111111')
        self.contacts.check_search_results(self.contact["givenName"])

        x = self.UTILS.element.getElement(DOM.Contacts.search_cancel_btn, "Search cancel button")
        x.tap()

        self.UTILS.reporting.logResult("info", "<b>Search against number in 'family name' field ...</b>")
        self.contacts.search('2222222')
        self.contacts.check_search_results(self.contact2["familyName"])
Esempio n. 24
0
class test_main(GaiaTestCase):
    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Create our test contacts.
        self.contact_list = [MockContact() for i in range(3)]
        map(self.UTILS.general.insertContact, self.contact_list)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # Search for our new contact.
        self.contacts.search(self.contact_list[0]["tel"]["value"])

        # Verify that we're now in the 'search results' screen.
        self.UTILS.element.waitForElements(DOM.Contacts.search_results_list,
                                           "Search results list")

        # Cancel the search.
        x = self.UTILS.element.getElement(DOM.Contacts.search_cancel_btn,
                                          "Cancel search button")
        x.tap()

        # Verify that we're no longer in the 'search results' screen.
        self.UTILS.element.waitForNotElements(DOM.Contacts.search_results_list,
                                              "Search results list")
Esempio n. 25
0
class test_main(GaiaTestCase):

    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        self.contact = MockContact(tel={'type': 'Mobile', 'value': '123111111'})
        self.contact2 = MockContact(tel={'type': 'Mobile', 'value': '123222222'})

        self.UTILS.general.insertContact(self.contact2)

    def tearDown(self):
        self.UTILS.general.remove_files()
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # Store our picture on the device.
        self.UTILS.general.add_file_to_device('./tests/_resources/contact_face.jpg')

        # Create and verify contact
        self.contacts.launch()
        self.contacts.create_contact(self.contact, "gallery")
        self.contacts.verify_image_in_all_contacts(self.contact['name'])

        # Search for our contacts.
        self.contacts.search("test")
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"])

        # Verify that the image is present for the right contact.
        results_list = self.UTILS.element.getElements(DOM.Contacts.search_results_list, "Search results")
        tuples = zip(results_list, [self.contact, self.contact2], [True, False])
        for t in tuples:
            ok = self.verify_img_for_contact(t[0], t[1], t[2])
            self.UTILS.test.test(ok, "Image was {}found (Expected: {})".format("" if ok else "not ", t[2]))

        screenshot = self.UTILS.debug.screenShotOnErr()
        self.UTILS.reporting.logResult("info", "Screenshot of search results", screenshot)

    def verify_img_for_contact(self, result, contact, expect_image):
        """Verify if an image is present for the result list item.

        The result item must be the specified by contact.
        Return True if the contact has a image and expected_image is True.
        False otherwise.
        """
        found = False
        if result.get_attribute("data-order") == contact["name"].replace(" ", "").upper():
            try:
                img = result.find_element("css selector", "li.contact-item[data-order*='{}'] span[data-type=img]".\
                                          format(contact['givenName']))
                if "blob" in img.get_attribute("data-src"):
                    found = True
            except:
                self.UTILS.reporting.logResult("info", "No image present for contact {} |"\
                                               " The image was indeed expected".format(result.text))
        else:
            self.UTILS.test.test(False, "This contact does not appear in the list: {}".format(result.text))
        res = found == expect_image
        return res
Esempio n. 26
0
class Messages(object):

    def __init__(self, parent):
        self.apps = parent.apps
        self.data_layer = parent.data_layer
        self.parent = parent
        self.marionette = parent.marionette
        self.UTILS = parent.UTILS
        self.actions = Actions(self.marionette)

    @retry(5)
    def launch(self):
        self.app = self.apps.launch(self.__class__.__name__)
        self.UTILS.element.waitForNotElements(DOM.GLOBAL.loading_overlay,
                                              self.__class__.__name__ + " app - loading overlay")
        return self.app

    def cancelSettings(self):
        self.UTILS.reporting.logResult("info", "Cliking on messages options button")
        options_btn = self.UTILS.element.getElement(DOM.Messages.messages_options_btn,
                                                    "Messages option button is displayed")
        options_btn.tap()

        # Press cancel button
        cancelBtn = self.UTILS.element.getElement(DOM.Messages.cancel_btn_msg,
                                                  "Press Cancel button")
        cancelBtn.tap()

    def deleteSubject(self, subject):
        self.UTILS.reporting.logResult("info", "Cliking on messages options button")
        x = self.UTILS.element.getElement(DOM.Messages.messages_options_btn,
                                          "Messages option button is displayed")
        x.tap()

        # Press add subject button
        self.UTILS.reporting.logResult("info", "Cliking on delete subject button")
        x = self.UTILS.element.getElement(DOM.Messages.deletesubject_btn_msg_opt,
                                          "delete subject option button is displayed")
        x.tap()

    def addSubject(self, subject):
        self.UTILS.reporting.logResult("info", "Cliking on messages options button")
        x = self.UTILS.element.getElement(DOM.Messages.messages_options_btn,
                                          "Messages option button is displayed")
        x.tap()

        # Press add subject button
        screenshot = self.UTILS.debug.screenShotOnErr()
        self.UTILS.reporting.logResult('info', "Screenshot", screenshot)

        self.UTILS.reporting.logResult("info", "Cliking on add subject button")
        x = self.UTILS.element.getElement(DOM.Messages.addsubject_btn_msg_opt,
                                          "add subject option button is displayed")
        x.tap()

        self.UTILS.general.typeThis(DOM.Messages.target_subject,
                                    "Target Subject  field",
                                    subject,
                                    p_no_keyboard=True,
                                    p_validate=False,
                                    p_clear=False,
                                    p_enter=False)

    def checkAirplaneModeWarning(self):
        """
        Checks for the presence of the popup
        warning message if you just sent a message
        while in 'airplane mode' (also removes
        the message so you can continue).
        """
        x = self.UTILS.element.getElement(DOM.Messages.airplane_warning_message,
                                          "Airplane mode warning message",
                                          True, 5, False)
        if x:
            self.UTILS.reporting.logResult("info",
                                           "Warning message title detected = '" + x.text + "'.")

            x = self.UTILS.element.getElement(DOM.Messages.airplane_warning_ok, "OK button")
            x.tap()

    def check_last_message_contents(self, expected, mms=False):
        """
        Get the last message text and check it against the expected value.
        """
        msg = self.last_message_in_this_thread()
        dom = DOM.Messages.last_message_mms_text if mms else DOM.Messages.last_message_text
        msg_text = self.marionette.find_element(*dom, id=msg.id)
        self.UTILS.test.test((msg_text and msg_text.text == expected),
                             u"Expected message text = '{}' ({}) (got '{}' ({})).".
                             format(expected, len(expected), msg_text.text, len(msg_text.text)))

    def checkIsInToField(self, target, targetIsPresent=True):
        """
        Verifies if a number (or contact name) is
        displayed in the "To: " field of a compose message.<br>
        (Uses 'caseless' search for this.)
        """
        time.sleep(1)
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers, "'To:' field contents", False)

        boolOK = False
        for i in x:
            if i.text.lower() == str(target).lower():
                boolOK = True
                break

        testMsg = "is" if targetIsPresent else "is not"
        testMsg = "\"" + str(target) + "\" " + testMsg + " in the 'To:' field."
        self.UTILS.test.test(boolOK == targetIsPresent, testMsg)
        return boolOK

    def checkMMSIcon(self, thread_name):

        # Get the thread for which we want to check the icon existence
        selector = ("xpath", DOM.Messages.thread_selector_xpath.format(thread_name))
        elem = self.UTILS.element.getElement(selector, "Message thread for " + thread_name)
        """
        But, in order to make sure we're getting the specific frame, what we trully
        got above is an inner child of the thread element. So, we gotta get the father
        """
        thread = self.marionette.execute_script("""
            return arguments[0].parentNode;
        """, script_args=[elem])

        # Checks for the presence of the MMS icon
        icon = thread.find_element(*DOM.Messages.mms_icon)
        if icon:
            self.UTILS.test.test(icon is not None, "MMS icon detected for thread [{}]".format(thread_name))

    def checkNumberIsInToField(self, target):
        """
        Verifies if a number is contained in the
        "To: " field of a compose message (even if it's
        not displayed - i.e. a contact name is displayed,
        but this validates the <i>number</i> for that
        contact).
        """
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers, "'To:' field contents")

        boolOK = False
        for i in x:
            if i.get_attribute("data-number") == target:
                boolOK = True
                break

        self.UTILS.test.test(boolOK,
                             "\"" + str(target) + "\" is the number in one of the 'To:' field targets.")
        return boolOK

    def checkThreadHeader(self, header):
        """
        Verifies if a string is contained in the header
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Header")

        boolOK = False
        if x.get_attribute("data-number") == header:
            boolOK = True

        self.UTILS.test.test(boolOK, "\"" + str(header) + "\" is the header in the SMS conversation.")
        return boolOK

    def checkThreadHeaderWithNameSurname(self, header):
        """
        Verifies if a string is contained in the header
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Header")

        boolOK = False

        if x.text == header:
            boolOK = True

        self.UTILS.test.test(boolOK, "\"" + header + "\" is the header in the SMS conversation.")
        return boolOK

    def closeThread(self):
        """
        Closes the current thread (returns you to the
        'thread list' SMS screen).
        """
        self.go_back()
        self.UTILS.element.waitForElements(("xpath", "//h1[text()='{}']".format(_("Messages"))),
                                           "Messages main header")

    def countMessagesInThisThread(self):
        """
        Returns the number of messages in this thread
        (assumes you're already in the thread).
        """
        try:
            return len(self.UTILS.element.getElements(DOM.Messages.message_list, "Messages"))
        except:
            return 0

    def countNumberOfThreads(self):
        """
        Count all threads (assumes the messagin app is already open).
        """
        try:
            return len(self.UTILS.element.getElements(DOM.Messages.threads_list, "Threads"))
        except:
            return 0

    def create_and_send_mms(self, attached_type, nums, m_text):

        self.gallery = Gallery(self.parent)
        self.video = Video(self.parent)
        self.music = Music(self.parent)

        self.launch()
        self.startNewSMS()
        self.addNumbersInToField(nums)
        self.enterSMSMsg(m_text)

        if attached_type == "image":
            # Add an image file
            self.UTILS.general.add_file_to_device('./tests/_resources/80x60.jpg')
            self.create_mms_image()
            self.gallery.click_on_thumbnail_at_position_mms(0)
        elif attached_type == "cameraImage":
            # Add an image file from camera
            self.create_mms_camera_image()
            time.sleep(3)
        elif attached_type == "video":
            # Load an video file into the device.
            self.UTILS.general.add_file_to_device('./tests/_resources/mpeg4.mp4')
            self.create_mms_video()
            self.video.click_on_video_at_position_mms(0)
        elif attached_type == "audio":
            # Load an video file into the device.
            self.UTILS.general.add_file_to_device('./tests/_resources/AMR.amr')
            self.create_mms_music()
            self.music.click_on_song_mms()
        else:
            # self.UTILS.reporting.logResult("info", "incorrect value received")
            msg = "FAILED: Incorrect parameter received in create_and_send_mms()"\
                ". attached_type must being image, video or audio."
            self.UTILS.test.test(False, msg)

        time.sleep(2)
        self.sendSMS()
        return self.last_sent_message_timestamp()

    def create_and_send_sms(self, nums, msg):
        """
        Create and send a new SMS.<br>
        <b>Note:</b> The nums field must be an array of numbers
        or contact names.
        """
        self.startNewSMS()
        self.addNumbersInToField(nums)
        self.enterSMSMsg(msg)

        # The header should now say how many recipients.
        time.sleep(2)  # give the header time to change.

        num_recs = len(nums)
        search_str = _(" recipient") if num_recs == 1 else _(" recipients")
        self.UTILS.element.headerCheck(str(num_recs) + search_str)

        # Send the message.
        self.sendSMS()

    def create_mms_image(self):
        attach = self.UTILS.element.getElement(DOM.Messages.attach_button, "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        gallery = self.UTILS.element.getElement(DOM.Messages.mms_from_gallery, "From gallery")
        gallery.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Gallery.frame_locator)

    def create_mms_camera_image(self):
        self.camera = Camera(self.parent)

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button, "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        camera = self.UTILS.element.getElement(DOM.Messages.mms_from_camera, "From Camera")
        camera.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Camera.frame_locator)

        # Take a picture.
        self.camera.take_and_select_picture()

        self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)

    def create_mms_music(self):

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button, "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        music = self.UTILS.element.getElement(DOM.Messages.mms_from_music, "From music")
        music.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Music.frame_locator)

    def go_back(self):
        """Press back button in messages thread
        """
        # TODO: remove tap with coordinates after Bug 1061698 is fixed
        self.UTILS.element.getElement(DOM.Messages.header_link_locator, "Back button").tap(25, 25)

    def create_mms_video(self):

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button, "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()

        video = self.UTILS.element.getElement(DOM.Messages.mms_from_video, "From video")
        video.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Video.frame_locator)

    def delete_all_threads(self):
        """
        Deletes all threads (assumes the messagin app is already open).
        """
        try:
            self.parent.wait_for_element_displayed(*DOM.Messages.no_threads_message, timeout=3)
            no_threads_message = self.marionette.find_element(*DOM.Messages.no_threads_message)
            if no_threads_message.is_displayed():
                self.UTILS.reporting.logResult("info", "(No message threads to delete.)")
        except:
            self.UTILS.reporting.logResult("info", "Deleting message threads ...")
            self.threadEditModeON()

            select_threads = self.UTILS.element.getElement(
                DOM.Messages.edit_msgs_select_threads_btn, "Delete threads button")
            select_threads.tap()

            select_all_btn = self.UTILS.element.getElement(DOM.Messages.check_all_threads_btn, "Select all button")
            select_all_btn.tap()

            self.deleteSelectedThreads()
            self.UTILS.element.waitForElements(DOM.Messages.no_threads_message,
                                               "No message threads notification", True, 60)

    def deleteMessagesInThisThread(self, msg_array=False):
        """
        Enters edit mode, selects the required messages and
        deletes them.<br>
        msg_array is an array of numbers.
        If it's not specified then all messages in this
        thread will be deleted.
        """
        if msg_array:
            self.editAndSelectMessages(msg_array)
        else:

            # Go into messages Settings..
            edit_btn = self.UTILS.element.getElement(DOM.Messages.edit_messages_icon, "Edit button")
            edit_btn.tap()

            select_btn = self.UTILS.element.getElement(DOM.Messages.edit_msgs_select_btn, "Select button")
            select_btn.tap()

            # Press select all button.
            select_all_btn = self.UTILS.element.getElement(DOM.Messages.check_all_messages_btn, "'Select all' button")
            select_all_btn.tap()

        self.deleteSelectedMessages()

    def deleteSelectedMessages(self):
        self.UTILS.reporting.debug("*** Tapping top Delete button")
        delete_btn = self.UTILS.element.getElement(DOM.Messages.delete_messages_ok_btn, "Delete button")
        delete_btn.tap()
        time.sleep(2)

        self.UTILS.reporting.debug("*** Tap Delete messages confirmation button")
        confirm_btn = self.UTILS.element.getElement(
            DOM.Messages.delete_threads_ok_btn, "Delete messages confirmation button")
        confirm_btn.tap()
        time.sleep(2)

    def deleteSelectedThreads(self):
        delete_btn = self.UTILS.element.getElement(DOM.Messages.threads_delete_button, "Delete threads button")
        delete_btn.tap()

        delete_confirm_btn = self.UTILS.element.getElement(
            DOM.Messages.delete_threads_ok_btn, "Delete threads confirmation button")
        delete_confirm_btn.tap()

    def deleteThreads(self, target_array=False):
        """
        Enters edit mode, selects the required messages and
        deletes them.<br>
        target_array is an array of target numbers
        or contacts which identify the threads to be selected.
        If it's not specified then all messages in this
        thread will be deleted.
        """
        try:
            self.parent.wait_for_element_displayed(*DOM.Messages.no_threads_message, timeout=2)
            x = self.marionette.find_element(*DOM.Messages.no_threads_message)
            if x.is_displayed():
                self.UTILS.reporting.logResult("info", "(No message threads to delete.)")
        except:
            self.UTILS.reporting.logResult("info", "Deleting message threads ...")
            if target_array:
                self.UTILS.reporting.debug("*** Selecting threads for deletion [{}]".format(target_array))
                self.editAndSelectThreads(target_array)
                self.UTILS.reporting.debug("*** Threads selected")
                self.deleteSelectedThreads()
            else:
                self.delete_all_threads()

    def editAndSelectMessages(self, msg_array):
        """
        Puts this thread into Edit mode and selects
        the messages listed in msg_array.<br>
        msg_array is an array of numbers.
        """
        edit_btn = self.UTILS.element.getElement(DOM.Messages.edit_messages_icon, "Edit button")
        edit_btn.tap()
        time.sleep(2)

        # Go into message edit mode..
        select_btn = self.UTILS.element.getElement(DOM.Messages.edit_msgs_select_btn, "Select messages button")
        select_btn.tap()
        time.sleep(2)

        messages = self.UTILS.element.getElements(DOM.Messages.message_list, "Messages")
        for msg in msg_array:
            messages[msg].tap()

    def editAndSelectThreads(self, target_array):
        """
        Puts this thread into Edit mode and selects
        the messages listed in p_msg_array.<br>
        target_array is an array of target numbers
        or contacts which identify the threads to be selected.
        """
        # Go into edit mode..
        self.threadEditModeON()

        select_btn = self.UTILS.element.getElement(DOM.Messages.edit_msgs_select_threads_btn, "Select threads button")
        select_btn.tap()

        if len(target_array) == 0:
            return

        for i in target_array:
            self.UTILS.reporting.debug("selecting thread for [{}]".format(i))
            thread = self.UTILS.element.getElement(("xpath", DOM.Messages.thread_selector_xpath.format(i)),
                                                   "Thread checkbox for '{}'".format(i))
            self.UTILS.reporting.debug("Trying to tap in element {}".format(thread))
            thread.tap()

        # Finally check that all desired threads have been selected
        header = self.UTILS.element.getElement(DOM.Messages.edit_threads_header, "Edit threads header").text
        expected_title = str(len(target_array)) if len(target_array) else _("Delete messages")
        self.UTILS.test.test(expected_title in header, "Check that all desired threads have been selected")

    def enterSMSMsg(self, msg, not_keyboard=True):
        """
        Create and send a message (assumes we are in a new 'create new message'
        screen with the destination number filled in already).
        """
        self.parent.wait_for_element_displayed(*DOM.Messages.input_message_area)
        input_area = self.marionette.find_element(*DOM.Messages.input_message_area)
        input_area.tap()
        input_area.send_keys(msg)

        # Validate the field.
        # Get the element again in order to avoid StaleElementException
        input_area = self.marionette.find_element(*DOM.Messages.input_message_area)
        self.UTILS.test.test(input_area.text == msg,
                             u'The text in the message area is "{}". Expected: "{}"'.format(input_area.text, msg))

    def addNumbersInToField(self, nums):
        """
        Add the phone numbers in the 'To' field of this sms message.
        Assumes you are in 'create sms' screen.
        """

        # This variable is used to keep track of the appearance of the keyboard frame
        n = 0

        for num in nums:
            """
            Even though we don't use the keyboard for putting the number in,
            we need it for the ENTER button (which allows us to put more than
            one number in).
            So check that the keyboard appears when we tap the "TO" field if we have
            more than one number.
            """
            if len(nums) > 1:
                self.UTILS.reporting.logResult("info", "Checking the keyboard appears when I tap the 'To' field ...")
                to_field = self.UTILS.element.getElement(DOM.Messages.target_numbers_empty, "Target number field")
                to_field.tap()

                boolKBD = False
                self.marionette.switch_to_frame()

                if n < 1:

                    try:
                        # A 'silent' check to see if the keyboard iframe appears.
                        elDef = ("xpath", "//iframe[contains(@{}, '{}')]".
                                 format(DOM.Keyboard.frame_locator[0], DOM.Keyboard.frame_locator[1]))
                        self.parent.wait_for_element_displayed(*elDef, timeout=2)
                        boolKBD = True
                    except:
                        boolKBD = False

                    self.UTILS.test.test(
                        boolKBD, "Keyboard is displayed when 'To' field is clicked for the first time")

                self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)

            if n == 0:

                self.UTILS.general.typeThis(DOM.Messages.target_numbers_empty,
                                            "Target number field",
                                            num,
                                            p_no_keyboard=True,
                                            p_validate=False,
                                            p_clear=False,
                                            p_enter=True)

            else:
                self.UTILS.general.typeThis(DOM.Messages.target_numbers_empty,
                                            "Target number field",
                                            num,
                                            p_no_keyboard=True,
                                            p_validate=False,
                                            p_clear=False,
                                            p_enter=False)
                input_area = self.UTILS.element.getElement(DOM.Messages.input_message_area, "Target number field")
                input_area.tap()

            n += 1

    def addContactToField(self, contact_name):
        self._search_for_contact(contact_name)
        # Now check the correct name is in the 'To' list.
        self.checkIsInToField(contact_name)

    def _select_forward_option_for(self, element):
        self.actions.long_press(element, 2).perform()
        self.UTILS.reporting.logResult("info", "Clicking on forward button")
        forward_option = self.UTILS.element.getElement(DOM.Messages.forward_btn_msg_opt, "Forward button is displayed")
        forward_option.tap()

    def _search_for_contact(self, contact_name):
        self.contacts = Contacts(self.parent)
        self.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

        self.contacts.search(contact_name)
        self.contacts.check_search_results(contact_name)

        results = self.UTILS.element.getElements(DOM.Contacts.search_results_list, "Contacts search results")
        for result in results:
            if result.text == contact_name:
                result.tap()
                break

        # Switch back to the sms iframe.
        self.apps.switch_to_displayed_app()

    def forwardMessage(self, msg_type, target_telNum):
        """
        Forwards the last message of the thread to a number
        """

        self.UTILS.reporting.logResult('info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            self.UTILS.reporting.logResult("info", "Open {} option with longtap on it".format(msg_type))
            last = self.last_message_in_this_thread()
            body = self.marionette.find_element(*DOM.Messages.last_message_body, id=last.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            self.UTILS.reporting.logResult("info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(DOM.Messages.received_mms_subject, "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        self.addNumbersInToField([target_telNum])

        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def forwardMessageToContact(self, msg_type, contact_name):
        """
        Forwards the last message of the thread to a contact, searching for it
        """
        self.UTILS.reporting.logResult('info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            # Open sms option with longtap on it
            self.UTILS.reporting.logResult("info", "Open sms option with longtap on it")
            sms = self.last_message_in_this_thread()
            body = self.marionette.find_element(*DOM.Messages.last_message_body, id=sms.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            # Open mms option with longtap on it
            self.UTILS.reporting.logResult("info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(DOM.Messages.received_mms_subject,
                                                        "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        # Search for the contact and check it's been added
        self.addContactToField(contact_name)

        # Send the mms.
        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def forwardMessageToMultipleRecipients(self, msg_type, target_telNum, contact_name):
        self.UTILS.reporting.logResult('info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            # Open sms option with longtap on it
            self.UTILS.reporting.logResult("info", "Open sms option with longtap on it")
            sms = self.last_message_in_this_thread()
            body = self.marionette.find_element(*DOM.Messages.last_message_body, id=sms.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            # Open mms option with longtap on it
            self.UTILS.reporting.logResult("info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(DOM.Messages.received_mms_subject,
                                                        "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        # Add phone numbers
        self.addNumbersInToField([target_telNum])
        # Search for the contact and check it's been added
        self.addContactToField(contact_name)

        # Send the mms.
        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def get_mms_attachments_info(self, mms):
        """Give name and file size for all attachments in an MMS.

        Given an MMS, return a list containing a dictionary for every attachment,
        with two keys, name and size.
        """
        attachment_names = self.marionette.find_elements(*DOM.Messages.mms_attachment_names, id=mms.id)
        attachment_sizes = self.marionette.find_elements(*DOM.Messages.mms_attachment_sizes, id=mms.id)
        result = []
        for (i, name) in enumerate(attachment_names):
            inner_text = self.marionette.execute_script("""return arguments[0].innerHTML;""", script_args=[name])
            att = {}
            att["name"] = inner_text
            size_elem = attachment_sizes[i].get_attribute("data-l10n-args")
            size = size_elem[size_elem.index(":") + 2:size_elem.rfind("\"")]
            i = i + 1
            att["size"] = size
            result.append(att)
        return result

    def getThreadText(self, num):
        """
        Returns the preview text for the thread for this number (if it exists),
        or False if either the thread doesn't exist or can't be found.
        """
        if self.threadExists(num):
            x = self.UTILS.element.getElements(DOM.Messages.threads_list, "Threads")

            for thread in x:
                try:
                    thread.find_element("xpath", ".//p[text()='{}']".format(num))
                    z = thread.find_element("xpath", ".//span[@class='body-text']")
                    return z.text
                except:
                    pass
        return False

    def header_addToContact(self):
        """
        Taps the header and tries to tap the 'Add to an existsing contact' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue (contacts).
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(DOM.Messages.header_add_to_contact_btn,
                                          "'Add to an existing contact' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

    def header_call(self):
        """Tap on the header of a messages thread and dial the number
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Thread header")
        x.tap()

        # Select dialer option.
        x = self.UTILS.element.getElement(DOM.Messages.header_call_btn, "'Call' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Dialer.frame_locator)

    def header_createContact(self):
        """
        Taps the header and tries to tap the 'send message' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue.
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(DOM.Messages.header_create_new_contact_btn,
                                          "'Create new contact' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

    def header_sendMessage(self):
        """
        Taps the header and tries to tap the 'send message' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue.
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header, "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(DOM.Messages.header_send_message_btn, "'Send message' button")
        x.tap()

    def last_message_in_this_thread(self):
        """
        Returns an object of the last message in the current thread.
        """
        self.parent.wait_for_element_present(*DOM.Messages.last_message, timeout=20)
        message = self.marionette.find_element(*DOM.Messages.last_message)
        self.UTILS.element.scroll_into_view(message)
        return message

    def last_sent_message_timestamp(self):
        """Returns the timestamp of the last sent message
        """
        send_time = self.marionette.find_element(*DOM.Messages.last_sent_message).get_attribute("data-timestamp")
        return float(send_time) / 1000

    def last_sent_message(self):
        """Returns the last sent message
        """
        return self.marionette.find_element(*DOM.Messages.last_sent_message)

    def open_attached_file(self, frame_to_change):
        elem = DOM.Messages.last_message_attachment_av
        last = self.UTILS.element.getElement(elem, "Last message attachment")
        self.UTILS.element.scroll_into_view(last)

        # Now get the thumbnail in order to open it
        thumb = last.find_element(*DOM.Messages.last_message_thumbnail)
        thumb.tap()
        self.UTILS.iframe.switchToFrame(*frame_to_change)

    def openThread(self, num):
        """
        Opens the thread for this number (assumes we're looking at the
        threads in the messaging screen).
        """
        try:
            thread_el = ("xpath", DOM.Messages.thread_selector_xpath.format(num))
            x = self.UTILS.element.getElement(thread_el, "Message thread for " + num)
            x.tap()

            self.UTILS.element.waitForElements(DOM.Messages.send_message_button, "'Send' button")
        except Exception as e:
            x = self.UTILS.debug.screenShotOnErr()
            msg = "<b>NOTE:</b> The thread <i>may</i> have failed to open due to [{}].".format(e)
            self.UTILS.reporting.logResult("info", msg, x)

    def readLastSMSInThread(self):
        """
        Read last message in the current thread.
        """
        received_message = self.UTILS.element.getElements(DOM.Messages.received_messages,
                                                          "Received messages")[-1]
        return str(received_message.text)

    def readNewSMS(self, fromNum):
        """
        Read and return the value of the new message received from number.
        """
        x = self.UTILS.element.getElement(("xpath", DOM.Messages.messages_from_num.format(fromNum)),
                                          "Message from '" + fromNum + "'")
        x.tap()

        # (From gaiatest: "TODO Due to displayed bugs I cannot find a good wait
        # for switch btw views")
        time.sleep(5)

        # Return the last comment in this thread.
        return self.readLastSMSInThread()

    def removeContactFromToField(self, target):
        """
        Removes target from the "To" field of this SMS.<br>
        Returns True if it found the target, or False if not.
        """
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers, "'To:' field contents")

        for i in range(len(x)):
            self.UTILS.reporting.logResult("info",
                                           "Checking target '{}' to '{}' ...".format(x[i].text, target))

            if x[i].text.lower() == target.lower():
                self.UTILS.reporting.logResult("info", "Tapping contact '" + target + "' ...")
                x[i].tap()

                try:

                    # This contact was added via 'add contact' icon.
                    self.parent.wait_for_element_displayed("xpath", "//button[text()='{}']".format(_("Remove")),
                                                           timeout=2)
                    y = self.marionette.find_element("xpath", "//button[text()='{}']".format(_("Remove")))
                    self.UTILS.reporting.logResult("info", "Tapping 'Remove' button.")
                    y.tap()
                    return True
                except:

                    # This contact was manually entered.
                    z = self.UTILS.element.getElements(DOM.Messages.target_numbers,
                                                       "Target to be removed")[i]
                    z.clear()
                    return True
        return False

    def selectAddContactButton(self):
        """
        Taps the 'add contact' button
        """
        add_btn = self.UTILS.element.getElement(DOM.Messages.add_contact_button, "Add contact button")
        add_btn.tap()

    def sendSMS(self):
        """
        Just presses the 'send' button (assumes everything else is done).
        """
        self.parent.wait_for_condition(lambda m: m.find_element(*DOM.Messages.send_message_button).is_enabled())
        send_btn = self.marionette.find_element(*DOM.Messages.send_message_button)
        send_btn.tap()

        # (Give the spinner time to appear.)
        time.sleep(2)
        self.UTILS.element.waitForNotElements(DOM.Messages.message_sending_spinner, "'Sending' icon", True, 180)

        # Check if we received the 'service unavailable' message.
        try:
            self.parent.wait_for_element_displayed(*DOM.Messages.service_unavailable_msg, timeout=2)
            screenshot = self.UTILS.debug.screenShotOnErr()
            msg = "'Service unavailable' message detected - unable to send sms!"
            self.UTILS.reporting.logResult("info", msg, screenshot)
            return False
        except:
            pass

        return True

    def startNewSMS(self):
        """
        Starts a new sms (doesn't fill anything in).
        Assumes the Messaging app is already launched.
        """
        newMsgBtn = self.UTILS.element.getElement(DOM.Messages.create_new_message_btn, "Create new message button")
        newMsgBtn.tap()

    def threadCarrier(self):

        # Returns the 'carrier' being used by this thread.
        x = self.UTILS.element.getElement(DOM.Messages.type_and_carrier_field, "Type and carrier information")
        parts = x.text.split("|")
        if len(parts) > 1:
            return parts[1].strip()
        return parts[0].strip()

    def threadEditModeOFF(self):
        """
        Turns off Edit mode while in the SMS threads screen.
        """
        x = self.UTILS.element.getElement(DOM.Messages.cancel_edit_threads, "Cancel button")
        x.tap()
        self.UTILS.element.waitForElements(DOM.Messages.edit_threads_button, "Edit button")

    def threadEditModeON(self):
        """
        Turns on Edit mode while in the SMS threads screen.
        """
        edit_btn = self.UTILS.element.getElement(DOM.Messages.edit_threads_button, "Edit button")
        edit_btn.tap()
        self.UTILS.element.waitForElements(DOM.Messages.cancel_edit_threads, "Cancel button")

    def threadExists(self, num):
        """
        Verifies that a thread exists for this number (returns True or False).
        """
        boolOK = False
        try:
            self.parent.wait_for_element_present("xpath", DOM.Messages.thread_selector_xpath.format(num), 1)
            boolOK = True
        except:
            boolOK = False

        return boolOK

    def threadType(self):
        """
        Returns the 'type' being used by this thread.
        """
        x = self.UTILS.element.getElement(DOM.Messages.type_and_carrier_field, "Type and carrier information")
        parts = x.text.split("|")
        typ = parts[0].strip()
        return typ if len(parts) > 1 else ''

    def time_of_last_message_in_thread(self):
        """
        Returns the time of the last message in the current thread.
        """
        t = self.UTILS.element.getElement(DOM.Messages.last_message_time, "Last message time")
        return t.text

    def time_of_thread(self, num):
        """
        Returns the time of a thread.
        """
        x = self.UTILS.element.getElement(("xpath", DOM.Messages.thread_timestamp_xpath.format(num)),
                                          "Thread time", True, 5, False)
        return x.text

    def thread_timestamp(self, num):
        """
        Returns the timestamp of a thread
        """
        x = self.marionette.find_element(*DOM.Messages.last_message).get_attribute("data-timestamp")
        return float(x)

    def verify_mms_received(self, attached_type, sender_number):

        self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)
        self.openThread(sender_number)
        message = self.last_message_in_this_thread()
        self.UTILS.test.test(message, "A received message appeared in the thread.", True)

        self.UTILS.reporting.debug("*** attached type: {}".format(attached_type))
        if attached_type == "img":
            elem = DOM.Messages.last_message_attachment_img
        elif attached_type == "video":
            elem = DOM.Messages.last_message_attachment_av
        elif attached_type == "audio":
            elem = DOM.Messages.last_message_attachment_av
        else:
            # self.UTILS.reporting.logResult("info", "incorrect value received")
            msg = "FAILED: Incorrect parameter received in verify_mms_received()"\
                ". Attached_type must be image, video or audio."
            self.UTILS.test.test(False, msg)

        self.UTILS.reporting.debug("*** searching for attachment type")
        # Look for all the attachments, since there can be more than one
        atts = self.UTILS.element.getElements(elem, "Last message attachments")
        self.UTILS.element.scroll_into_view(atts[0])
        found = False
        for att in atts:
            typ = att.get_attribute("data-attachment-type")
            self.UTILS.reporting.debug("*** searching for attachment type Result: {}".format(typ))
            if typ == attached_type:
                found = True
        if not found:
            msg = "No attachment with type {} was found in the message".format(attached_type)
            self.UTILS.test.test(False, msg)

    def wait_for_message(self, send_time=None, timeout=120):
        """Wait for a received message in the current thread and return it.
        """
        if not send_time:
            send_time = self.last_sent_message_timestamp()

        poll_time = 2
        poll_reps = (timeout / poll_time)
        result = False

        for i in range(poll_reps):
            # Get last message in this thread.
            last_msg = self.last_message_in_this_thread()

            if not last_msg:
                time.sleep(poll_time)
                continue

            # If the send_time timestamp is greater than this message's timestamp,it means the message
            # we expect has not arrived yet, so we have to wait a bit more.
            message_data_time = float(last_msg.get_attribute("data-timestamp")) / 1000
            fmt = "data-timestamp of last message in thread: {:.3f} send_time: {:.3f} --> {}"
            self.UTILS.reporting.debug(fmt.format(message_data_time, send_time, send_time > message_data_time))
            if send_time > message_data_time:
                continue

            # Is this a received message?
            if "incoming" in last_msg.get_attribute("class"):
                result = last_msg
                break

            # Nope - sleep then try again.
            time.sleep(poll_time)

        self.UTILS.test.test(result, "Last message in thread 'received' within {} seconds.".
                             format(timeout))
        return result
Esempio n. 27
0
class Messages(object):
    def __init__(self, parent):
        self.apps = parent.apps
        self.data_layer = parent.data_layer
        self.parent = parent
        self.marionette = parent.marionette
        self.UTILS = parent.UTILS
        self.actions = Actions(self.marionette)

    @retry(5)
    def launch(self):
        self.app = self.apps.launch(self.__class__.__name__)
        self.UTILS.element.waitForNotElements(
            DOM.GLOBAL.loading_overlay,
            self.__class__.__name__ + " app - loading overlay")
        return self.app

    def cancelSettings(self):
        self.UTILS.reporting.logResult("info",
                                       "Cliking on messages options button")
        options_btn = self.UTILS.element.getElement(
            DOM.Messages.messages_options_btn,
            "Messages option button is displayed")
        options_btn.tap()

        # Press cancel button
        cancelBtn = self.UTILS.element.getElement(DOM.Messages.cancel_btn_msg,
                                                  "Press Cancel button")
        cancelBtn.tap()

    def deleteSubject(self, subject):
        self.UTILS.reporting.logResult("info",
                                       "Cliking on messages options button")
        x = self.UTILS.element.getElement(
            DOM.Messages.messages_options_btn,
            "Messages option button is displayed")
        x.tap()

        # Press add subject button
        self.UTILS.reporting.logResult("info",
                                       "Cliking on delete subject button")
        x = self.UTILS.element.getElement(
            DOM.Messages.deletesubject_btn_msg_opt,
            "delete subject option button is displayed")
        x.tap()

    def addSubject(self, subject):
        self.UTILS.reporting.logResult("info",
                                       "Cliking on messages options button")
        x = self.UTILS.element.getElement(
            DOM.Messages.messages_options_btn,
            "Messages option button is displayed")
        x.tap()

        # Press add subject button
        screenshot = self.UTILS.debug.screenShotOnErr()
        self.UTILS.reporting.logResult('info', "Screenshot", screenshot)

        self.UTILS.reporting.logResult("info", "Cliking on add subject button")
        x = self.UTILS.element.getElement(
            DOM.Messages.addsubject_btn_msg_opt,
            "add subject option button is displayed")
        x.tap()

        self.UTILS.general.typeThis(DOM.Messages.target_subject,
                                    "Target Subject  field",
                                    subject,
                                    p_no_keyboard=True,
                                    p_validate=False,
                                    p_clear=False,
                                    p_enter=False)

    def checkAirplaneModeWarning(self):
        """
        Checks for the presence of the popup
        warning message if you just sent a message
        while in 'airplane mode' (also removes
        the message so you can continue).
        """
        x = self.UTILS.element.getElement(
            DOM.Messages.airplane_warning_message,
            "Airplane mode warning message", True, 5, False)
        if x:
            self.UTILS.reporting.logResult(
                "info", "Warning message title detected = '" + x.text + "'.")

            x = self.UTILS.element.getElement(DOM.Messages.airplane_warning_ok,
                                              "OK button")
            x.tap()

    def check_last_message_contents(self, expected, mms=False):
        """
        Get the last message text and check it against the expected value.
        """
        msg = self.last_message_in_this_thread()
        dom = DOM.Messages.last_message_mms_text if mms else DOM.Messages.last_message_text
        msg_text = self.marionette.find_element(*dom, id=msg.id)
        self.UTILS.test.test(
            (msg_text and msg_text.text == expected),
            u"Expected message text = '{}' ({}) (got '{}' ({})).".format(
                expected, len(expected), msg_text.text, len(msg_text.text)))

    def checkIsInToField(self, target, targetIsPresent=True):
        """
        Verifies if a number (or contact name) is
        displayed in the "To: " field of a compose message.<br>
        (Uses 'caseless' search for this.)
        """
        time.sleep(1)
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers,
                                           "'To:' field contents", False)

        boolOK = False
        for i in x:
            if i.text.lower() == str(target).lower():
                boolOK = True
                break

        testMsg = "is" if targetIsPresent else "is not"
        testMsg = "\"" + str(target) + "\" " + testMsg + " in the 'To:' field."
        self.UTILS.test.test(boolOK == targetIsPresent, testMsg)
        return boolOK

    def checkMMSIcon(self, thread_name):

        # Get the thread for which we want to check the icon existence
        selector = ("xpath",
                    DOM.Messages.thread_selector_xpath.format(thread_name))
        elem = self.UTILS.element.getElement(
            selector, "Message thread for " + thread_name)
        """
        But, in order to make sure we're getting the specific frame, what we trully
        got above is an inner child of the thread element. So, we gotta get the father
        """
        thread = self.marionette.execute_script("""
            return arguments[0].parentNode;
        """,
                                                script_args=[elem])

        # Checks for the presence of the MMS icon
        icon = thread.find_element(*DOM.Messages.mms_icon)
        if icon:
            self.UTILS.test.test(
                icon is not None,
                "MMS icon detected for thread [{}]".format(thread_name))

    def checkNumberIsInToField(self, target):
        """
        Verifies if a number is contained in the
        "To: " field of a compose message (even if it's
        not displayed - i.e. a contact name is displayed,
        but this validates the <i>number</i> for that
        contact).
        """
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers,
                                           "'To:' field contents")

        boolOK = False
        for i in x:
            if i.get_attribute("data-number") == target:
                boolOK = True
                break

        self.UTILS.test.test(
            boolOK, "\"" + str(target) +
            "\" is the number in one of the 'To:' field targets.")
        return boolOK

    def checkThreadHeader(self, header):
        """
        Verifies if a string is contained in the header
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Header")

        boolOK = False
        if x.get_attribute("data-number") == header:
            boolOK = True

        self.UTILS.test.test(
            boolOK,
            "\"" + str(header) + "\" is the header in the SMS conversation.")
        return boolOK

    def checkThreadHeaderWithNameSurname(self, header):
        """
        Verifies if a string is contained in the header
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Header")

        boolOK = False

        if x.text == header:
            boolOK = True

        self.UTILS.test.test(
            boolOK,
            "\"" + header + "\" is the header in the SMS conversation.")
        return boolOK

    def closeThread(self):
        """
        Closes the current thread (returns you to the
        'thread list' SMS screen).
        """
        self.go_back()
        self.UTILS.element.waitForElements(
            ("xpath", "//h1[text()='{}']".format(_("Messages"))),
            "Messages main header")

    def countMessagesInThisThread(self):
        """
        Returns the number of messages in this thread
        (assumes you're already in the thread).
        """
        try:
            return len(
                self.UTILS.element.getElements(DOM.Messages.message_list,
                                               "Messages"))
        except:
            return 0

    def countNumberOfThreads(self):
        """
        Count all threads (assumes the messagin app is already open).
        """
        try:
            return len(
                self.UTILS.element.getElements(DOM.Messages.threads_list,
                                               "Threads"))
        except:
            return 0

    def create_and_send_mms(self, attached_type, nums, m_text):

        self.gallery = Gallery(self.parent)
        self.video = Video(self.parent)
        self.music = Music(self.parent)

        self.launch()
        self.startNewSMS()
        self.addNumbersInToField(nums)
        self.enterSMSMsg(m_text)

        if attached_type == "image":
            # Add an image file
            self.UTILS.general.add_file_to_device(
                './tests/_resources/80x60.jpg')
            self.create_mms_image()
            self.gallery.click_on_thumbnail_at_position_mms(0)
        elif attached_type == "cameraImage":
            # Add an image file from camera
            self.create_mms_camera_image()
            time.sleep(3)
        elif attached_type == "video":
            # Load an video file into the device.
            self.UTILS.general.add_file_to_device(
                './tests/_resources/mpeg4.mp4')
            self.create_mms_video()
            self.video.click_on_video_at_position_mms(0)
        elif attached_type == "audio":
            # Load an video file into the device.
            self.UTILS.general.add_file_to_device('./tests/_resources/AMR.amr')
            self.create_mms_music()
            self.music.click_on_song_mms()
        else:
            # self.UTILS.reporting.logResult("info", "incorrect value received")
            msg = "FAILED: Incorrect parameter received in create_and_send_mms()"\
                ". attached_type must being image, video or audio."
            self.UTILS.test.test(False, msg)

        time.sleep(2)
        self.sendSMS()
        return self.last_sent_message_timestamp()

    def create_and_send_sms(self, nums, msg):
        """
        Create and send a new SMS.<br>
        <b>Note:</b> The nums field must be an array of numbers
        or contact names.
        """
        self.startNewSMS()
        self.addNumbersInToField(nums)
        self.enterSMSMsg(msg)

        # The header should now say how many recipients.
        time.sleep(2)  # give the header time to change.

        num_recs = len(nums)
        search_str = _(" recipient") if num_recs == 1 else _(" recipients")
        self.UTILS.element.headerCheck(str(num_recs) + search_str)

        # Send the message.
        self.sendSMS()

    def create_mms_image(self):
        attach = self.UTILS.element.getElement(DOM.Messages.attach_button,
                                               "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        gallery = self.UTILS.element.getElement(DOM.Messages.mms_from_gallery,
                                                "From gallery")
        gallery.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Gallery.frame_locator)

    def create_mms_camera_image(self):
        self.camera = Camera(self.parent)

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button,
                                               "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        camera = self.UTILS.element.getElement(DOM.Messages.mms_from_camera,
                                               "From Camera")
        camera.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Camera.frame_locator)

        # Take a picture.
        self.camera.take_and_select_picture()

        self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)

    def create_mms_music(self):

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button,
                                               "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()
        music = self.UTILS.element.getElement(DOM.Messages.mms_from_music,
                                              "From music")
        music.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Music.frame_locator)

    def go_back(self):
        """Press back button in messages thread
        """
        # TODO: remove tap with coordinates after Bug 1061698 is fixed
        self.UTILS.element.getElement(DOM.Messages.header_link_locator,
                                      "Back button").tap(25, 25)

    def create_mms_video(self):

        attach = self.UTILS.element.getElement(DOM.Messages.attach_button,
                                               "Attach button")
        attach.tap()

        self.marionette.switch_to_frame()

        video = self.UTILS.element.getElement(DOM.Messages.mms_from_video,
                                              "From video")
        video.tap()

        self.UTILS.iframe.switchToFrame(*DOM.Video.frame_locator)

    def delete_all_threads(self):
        """
        Deletes all threads (assumes the messagin app is already open).
        """
        try:
            self.parent.wait_for_element_displayed(
                *DOM.Messages.no_threads_message, timeout=3)
            no_threads_message = self.marionette.find_element(
                *DOM.Messages.no_threads_message)
            if no_threads_message.is_displayed():
                self.UTILS.reporting.logResult(
                    "info", "(No message threads to delete.)")
        except:
            self.UTILS.reporting.logResult("info",
                                           "Deleting message threads ...")
            self.threadEditModeON()

            select_threads = self.UTILS.element.getElement(
                DOM.Messages.edit_msgs_select_threads_btn,
                "Delete threads button")
            select_threads.tap()

            select_all_btn = self.UTILS.element.getElement(
                DOM.Messages.check_all_threads_btn, "Select all button")
            select_all_btn.tap()

            self.deleteSelectedThreads()
            self.UTILS.element.waitForElements(
                DOM.Messages.no_threads_message,
                "No message threads notification", True, 60)

    def deleteMessagesInThisThread(self, msg_array=False):
        """
        Enters edit mode, selects the required messages and
        deletes them.<br>
        msg_array is an array of numbers.
        If it's not specified then all messages in this
        thread will be deleted.
        """
        if msg_array:
            self.editAndSelectMessages(msg_array)
        else:

            # Go into messages Settings..
            edit_btn = self.UTILS.element.getElement(
                DOM.Messages.edit_messages_icon, "Edit button")
            edit_btn.tap()

            select_btn = self.UTILS.element.getElement(
                DOM.Messages.edit_msgs_select_btn, "Select button")
            select_btn.tap()

            # Press select all button.
            select_all_btn = self.UTILS.element.getElement(
                DOM.Messages.check_all_messages_btn, "'Select all' button")
            select_all_btn.tap()

        self.deleteSelectedMessages()

    def deleteSelectedMessages(self):
        self.UTILS.reporting.debug("*** Tapping top Delete button")
        delete_btn = self.UTILS.element.getElement(
            DOM.Messages.delete_messages_ok_btn, "Delete button")
        delete_btn.tap()
        time.sleep(2)

        self.UTILS.reporting.debug(
            "*** Tap Delete messages confirmation button")
        confirm_btn = self.UTILS.element.getElement(
            DOM.Messages.delete_threads_ok_btn,
            "Delete messages confirmation button")
        confirm_btn.tap()
        time.sleep(2)

    def deleteSelectedThreads(self):
        delete_btn = self.UTILS.element.getElement(
            DOM.Messages.threads_delete_button, "Delete threads button")
        delete_btn.tap()

        delete_confirm_btn = self.UTILS.element.getElement(
            DOM.Messages.delete_threads_ok_btn,
            "Delete threads confirmation button")
        delete_confirm_btn.tap()

    def deleteThreads(self, target_array=False):
        """
        Enters edit mode, selects the required messages and
        deletes them.<br>
        target_array is an array of target numbers
        or contacts which identify the threads to be selected.
        If it's not specified then all messages in this
        thread will be deleted.
        """
        try:
            self.parent.wait_for_element_displayed(
                *DOM.Messages.no_threads_message, timeout=2)
            x = self.marionette.find_element(*DOM.Messages.no_threads_message)
            if x.is_displayed():
                self.UTILS.reporting.logResult(
                    "info", "(No message threads to delete.)")
        except:
            self.UTILS.reporting.logResult("info",
                                           "Deleting message threads ...")
            if target_array:
                self.UTILS.reporting.debug(
                    "*** Selecting threads for deletion [{}]".format(
                        target_array))
                self.editAndSelectThreads(target_array)
                self.UTILS.reporting.debug("*** Threads selected")
                self.deleteSelectedThreads()
            else:
                self.delete_all_threads()

    def editAndSelectMessages(self, msg_array):
        """
        Puts this thread into Edit mode and selects
        the messages listed in msg_array.<br>
        msg_array is an array of numbers.
        """
        edit_btn = self.UTILS.element.getElement(
            DOM.Messages.edit_messages_icon, "Edit button")
        edit_btn.tap()
        time.sleep(2)

        # Go into message edit mode..
        select_btn = self.UTILS.element.getElement(
            DOM.Messages.edit_msgs_select_btn, "Select messages button")
        select_btn.tap()
        time.sleep(2)

        messages = self.UTILS.element.getElements(DOM.Messages.message_list,
                                                  "Messages")
        for msg in msg_array:
            messages[msg].tap()

    def editAndSelectThreads(self, target_array):
        """
        Puts this thread into Edit mode and selects
        the messages listed in p_msg_array.<br>
        target_array is an array of target numbers
        or contacts which identify the threads to be selected.
        """
        # Go into edit mode..
        self.threadEditModeON()

        select_btn = self.UTILS.element.getElement(
            DOM.Messages.edit_msgs_select_threads_btn, "Select threads button")
        select_btn.tap()

        if len(target_array) == 0:
            return

        for i in target_array:
            self.UTILS.reporting.debug("selecting thread for [{}]".format(i))
            thread = self.UTILS.element.getElement(
                ("xpath", DOM.Messages.thread_selector_xpath.format(i)),
                "Thread checkbox for '{}'".format(i))
            self.UTILS.reporting.debug(
                "Trying to tap in element {}".format(thread))
            thread.tap()

        # Finally check that all desired threads have been selected
        header = self.UTILS.element.getElement(
            DOM.Messages.edit_threads_header, "Edit threads header").text
        expected_title = str(
            len(target_array)) if len(target_array) else _("Delete messages")
        self.UTILS.test.test(
            expected_title in header,
            "Check that all desired threads have been selected")

    def enterSMSMsg(self, msg, not_keyboard=True):
        """
        Create and send a message (assumes we are in a new 'create new message'
        screen with the destination number filled in already).
        """
        self.parent.wait_for_element_displayed(
            *DOM.Messages.input_message_area)
        input_area = self.marionette.find_element(
            *DOM.Messages.input_message_area)
        input_area.tap()
        input_area.send_keys(msg)

        # Validate the field.
        # Get the element again in order to avoid StaleElementException
        input_area = self.marionette.find_element(
            *DOM.Messages.input_message_area)
        self.UTILS.test.test(
            input_area.text == msg,
            u'The text in the message area is "{}". Expected: "{}"'.format(
                input_area.text, msg))

    def addNumbersInToField(self, nums):
        """
        Add the phone numbers in the 'To' field of this sms message.
        Assumes you are in 'create sms' screen.
        """

        # This variable is used to keep track of the appearance of the keyboard frame
        n = 0

        for num in nums:
            """
            Even though we don't use the keyboard for putting the number in,
            we need it for the ENTER button (which allows us to put more than
            one number in).
            So check that the keyboard appears when we tap the "TO" field if we have
            more than one number.
            """
            if len(nums) > 1:
                self.UTILS.reporting.logResult(
                    "info",
                    "Checking the keyboard appears when I tap the 'To' field ..."
                )
                to_field = self.UTILS.element.getElement(
                    DOM.Messages.target_numbers_empty, "Target number field")
                to_field.tap()

                boolKBD = False
                self.marionette.switch_to_frame()

                if n < 1:

                    try:
                        # A 'silent' check to see if the keyboard iframe appears.
                        elDef = ("xpath",
                                 "//iframe[contains(@{}, '{}')]".format(
                                     DOM.Keyboard.frame_locator[0],
                                     DOM.Keyboard.frame_locator[1]))
                        self.parent.wait_for_element_displayed(*elDef,
                                                               timeout=2)
                        boolKBD = True
                    except:
                        boolKBD = False

                    self.UTILS.test.test(
                        boolKBD,
                        "Keyboard is displayed when 'To' field is clicked for the first time"
                    )

                self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)

            if n == 0:

                self.UTILS.general.typeThis(DOM.Messages.target_numbers_empty,
                                            "Target number field",
                                            num,
                                            p_no_keyboard=True,
                                            p_validate=False,
                                            p_clear=False,
                                            p_enter=True)

            else:
                self.UTILS.general.typeThis(DOM.Messages.target_numbers_empty,
                                            "Target number field",
                                            num,
                                            p_no_keyboard=True,
                                            p_validate=False,
                                            p_clear=False,
                                            p_enter=False)
                input_area = self.UTILS.element.getElement(
                    DOM.Messages.input_message_area, "Target number field")
                input_area.tap()

            n += 1

    def addContactToField(self, contact_name):
        self._search_for_contact(contact_name)
        # Now check the correct name is in the 'To' list.
        self.checkIsInToField(contact_name)

    def _select_forward_option_for(self, element):
        self.actions.long_press(element, 2).perform()
        self.UTILS.reporting.logResult("info", "Clicking on forward button")
        forward_option = self.UTILS.element.getElement(
            DOM.Messages.forward_btn_msg_opt, "Forward button is displayed")
        forward_option.tap()

    def _search_for_contact(self, contact_name):
        self.contacts = Contacts(self.parent)
        self.selectAddContactButton()
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

        self.contacts.search(contact_name)
        self.contacts.check_search_results(contact_name)

        results = self.UTILS.element.getElements(
            DOM.Contacts.search_results_list, "Contacts search results")
        for result in results:
            if result.text == contact_name:
                result.tap()
                break

        # Switch back to the sms iframe.
        self.apps.switch_to_displayed_app()

    def forwardMessage(self, msg_type, target_telNum):
        """
        Forwards the last message of the thread to a number
        """

        self.UTILS.reporting.logResult(
            'info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            self.UTILS.reporting.logResult(
                "info", "Open {} option with longtap on it".format(msg_type))
            last = self.last_message_in_this_thread()
            body = self.marionette.find_element(
                *DOM.Messages.last_message_body, id=last.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            self.UTILS.reporting.logResult(
                "info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(
                DOM.Messages.received_mms_subject, "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        self.addNumbersInToField([target_telNum])

        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def forwardMessageToContact(self, msg_type, contact_name):
        """
        Forwards the last message of the thread to a contact, searching for it
        """
        self.UTILS.reporting.logResult(
            'info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            # Open sms option with longtap on it
            self.UTILS.reporting.logResult(
                "info", "Open sms option with longtap on it")
            sms = self.last_message_in_this_thread()
            body = self.marionette.find_element(
                *DOM.Messages.last_message_body, id=sms.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            # Open mms option with longtap on it
            self.UTILS.reporting.logResult(
                "info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(
                DOM.Messages.received_mms_subject, "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        # Search for the contact and check it's been added
        self.addContactToField(contact_name)

        # Send the mms.
        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def forwardMessageToMultipleRecipients(self, msg_type, target_telNum,
                                           contact_name):
        self.UTILS.reporting.logResult(
            'info', "The message type to forward is: {}".format(msg_type))

        if msg_type == "sms" or msg_type == "mms":
            # Open sms option with longtap on it
            self.UTILS.reporting.logResult(
                "info", "Open sms option with longtap on it")
            sms = self.last_message_in_this_thread()
            body = self.marionette.find_element(
                *DOM.Messages.last_message_body, id=sms.id)
            self._select_forward_option_for(body)

        elif msg_type == "mmssub":
            # Open mms option with longtap on it
            self.UTILS.reporting.logResult(
                "info", "Open mms with subject options with longtap on it")
            mms_subject = self.UTILS.element.getElement(
                DOM.Messages.received_mms_subject, "Target MMS field")
            self._select_forward_option_for(mms_subject)

        else:
            self.UTILS.reporting.logResult("info", "incorrect value received")
            self.UTILS.test.test(False, "Incorrect value received")

        # Add phone numbers
        self.addNumbersInToField([target_telNum])
        # Search for the contact and check it's been added
        self.addContactToField(contact_name)

        # Send the mms.
        self.UTILS.reporting.logResult("info", "Clicking on Send button")
        self.sendSMS()

    def get_mms_attachments_info(self, mms):
        """Give name and file size for all attachments in an MMS.

        Given an MMS, return a list containing a dictionary for every attachment,
        with two keys, name and size.
        """
        attachment_names = self.marionette.find_elements(
            *DOM.Messages.mms_attachment_names, id=mms.id)
        attachment_sizes = self.marionette.find_elements(
            *DOM.Messages.mms_attachment_sizes, id=mms.id)
        result = []
        for (i, name) in enumerate(attachment_names):
            inner_text = self.marionette.execute_script(
                """return arguments[0].innerHTML;""", script_args=[name])
            att = {}
            att["name"] = inner_text
            size_elem = attachment_sizes[i].get_attribute("data-l10n-args")
            size = size_elem[size_elem.index(":") + 2:size_elem.rfind("\"")]
            i = i + 1
            att["size"] = size
            result.append(att)
        return result

    def getThreadText(self, num):
        """
        Returns the preview text for the thread for this number (if it exists),
        or False if either the thread doesn't exist or can't be found.
        """
        if self.threadExists(num):
            x = self.UTILS.element.getElements(DOM.Messages.threads_list,
                                               "Threads")

            for thread in x:
                try:
                    thread.find_element("xpath",
                                        ".//p[text()='{}']".format(num))
                    z = thread.find_element("xpath",
                                            ".//span[@class='body-text']")
                    return z.text
                except:
                    pass
        return False

    def header_addToContact(self):
        """
        Taps the header and tries to tap the 'Add to an existsing contact' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue (contacts).
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(
            DOM.Messages.header_add_to_contact_btn,
            "'Add to an existing contact' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

    def header_call(self):
        """Tap on the header of a messages thread and dial the number
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Thread header")
        x.tap()

        # Select dialer option.
        x = self.UTILS.element.getElement(DOM.Messages.header_call_btn,
                                          "'Call' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Dialer.frame_locator)

    def header_createContact(self):
        """
        Taps the header and tries to tap the 'send message' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue.
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(
            DOM.Messages.header_create_new_contact_btn,
            "'Create new contact' button")
        x.tap()

        # Switch to correct iframe.
        self.UTILS.iframe.switchToFrame(*DOM.Contacts.frame_locator)

    def header_sendMessage(self):
        """
        Taps the header and tries to tap the 'send message' button.
        - Assumes we are looking at a message thread already.
        - Leaves you in the correct iframe to continue.
        """
        x = self.UTILS.element.getElement(DOM.Messages.message_header,
                                          "Thread header")
        x.tap()

        x = self.UTILS.element.getElement(DOM.Messages.header_send_message_btn,
                                          "'Send message' button")
        x.tap()

    def last_message_in_this_thread(self):
        """
        Returns an object of the last message in the current thread.
        """
        self.parent.wait_for_element_present(*DOM.Messages.last_message,
                                             timeout=20)
        message = self.marionette.find_element(*DOM.Messages.last_message)
        self.UTILS.element.scroll_into_view(message)
        return message

    def last_sent_message_timestamp(self):
        """Returns the timestamp of the last sent message
        """
        send_time = self.marionette.find_element(
            *DOM.Messages.last_sent_message).get_attribute("data-timestamp")
        return float(send_time) / 1000

    def last_sent_message(self):
        """Returns the last sent message
        """
        return self.marionette.find_element(*DOM.Messages.last_sent_message)

    def open_attached_file(self, frame_to_change):
        elem = DOM.Messages.last_message_attachment_av
        last = self.UTILS.element.getElement(elem, "Last message attachment")
        self.UTILS.element.scroll_into_view(last)

        # Now get the thumbnail in order to open it
        thumb = last.find_element(*DOM.Messages.last_message_thumbnail)
        thumb.tap()
        self.UTILS.iframe.switchToFrame(*frame_to_change)

    def openThread(self, num):
        """
        Opens the thread for this number (assumes we're looking at the
        threads in the messaging screen).
        """
        try:
            thread_el = ("xpath",
                         DOM.Messages.thread_selector_xpath.format(num))
            x = self.UTILS.element.getElement(thread_el,
                                              "Message thread for " + num)
            x.tap()

            self.UTILS.element.waitForElements(
                DOM.Messages.send_message_button, "'Send' button")
        except Exception as e:
            x = self.UTILS.debug.screenShotOnErr()
            msg = "<b>NOTE:</b> The thread <i>may</i> have failed to open due to [{}].".format(
                e)
            self.UTILS.reporting.logResult("info", msg, x)

    def readLastSMSInThread(self):
        """
        Read last message in the current thread.
        """
        received_message = self.UTILS.element.getElements(
            DOM.Messages.received_messages, "Received messages")[-1]
        return str(received_message.text)

    def readNewSMS(self, fromNum):
        """
        Read and return the value of the new message received from number.
        """
        x = self.UTILS.element.getElement(
            ("xpath", DOM.Messages.messages_from_num.format(fromNum)),
            "Message from '" + fromNum + "'")
        x.tap()

        # (From gaiatest: "TODO Due to displayed bugs I cannot find a good wait
        # for switch btw views")
        time.sleep(5)

        # Return the last comment in this thread.
        return self.readLastSMSInThread()

    def removeContactFromToField(self, target):
        """
        Removes target from the "To" field of this SMS.<br>
        Returns True if it found the target, or False if not.
        """
        x = self.UTILS.element.getElements(DOM.Messages.target_numbers,
                                           "'To:' field contents")

        for i in range(len(x)):
            self.UTILS.reporting.logResult(
                "info",
                "Checking target '{}' to '{}' ...".format(x[i].text, target))

            if x[i].text.lower() == target.lower():
                self.UTILS.reporting.logResult(
                    "info", "Tapping contact '" + target + "' ...")
                x[i].tap()

                try:

                    # This contact was added via 'add contact' icon.
                    self.parent.wait_for_element_displayed(
                        "xpath",
                        "//button[text()='{}']".format(_("Remove")),
                        timeout=2)
                    y = self.marionette.find_element(
                        "xpath", "//button[text()='{}']".format(_("Remove")))
                    self.UTILS.reporting.logResult("info",
                                                   "Tapping 'Remove' button.")
                    y.tap()
                    return True
                except:

                    # This contact was manually entered.
                    z = self.UTILS.element.getElements(
                        DOM.Messages.target_numbers, "Target to be removed")[i]
                    z.clear()
                    return True
        return False

    def selectAddContactButton(self):
        """
        Taps the 'add contact' button
        """
        add_btn = self.UTILS.element.getElement(
            DOM.Messages.add_contact_button, "Add contact button")
        add_btn.tap()

    def sendSMS(self):
        """
        Just presses the 'send' button (assumes everything else is done).
        """
        self.parent.wait_for_condition(lambda m: m.find_element(
            *DOM.Messages.send_message_button).is_enabled())
        send_btn = self.marionette.find_element(
            *DOM.Messages.send_message_button)
        send_btn.tap()

        # (Give the spinner time to appear.)
        time.sleep(2)
        self.UTILS.element.waitForNotElements(
            DOM.Messages.message_sending_spinner, "'Sending' icon", True, 180)

        # Check if we received the 'service unavailable' message.
        try:
            self.parent.wait_for_element_displayed(
                *DOM.Messages.service_unavailable_msg, timeout=2)
            screenshot = self.UTILS.debug.screenShotOnErr()
            msg = "'Service unavailable' message detected - unable to send sms!"
            self.UTILS.reporting.logResult("info", msg, screenshot)
            return False
        except:
            pass

        return True

    def startNewSMS(self):
        """
        Starts a new sms (doesn't fill anything in).
        Assumes the Messaging app is already launched.
        """
        newMsgBtn = self.UTILS.element.getElement(
            DOM.Messages.create_new_message_btn, "Create new message button")
        newMsgBtn.tap()

    def threadCarrier(self):

        # Returns the 'carrier' being used by this thread.
        x = self.UTILS.element.getElement(DOM.Messages.type_and_carrier_field,
                                          "Type and carrier information")
        parts = x.text.split("|")
        if len(parts) > 1:
            return parts[1].strip()
        return parts[0].strip()

    def threadEditModeOFF(self):
        """
        Turns off Edit mode while in the SMS threads screen.
        """
        x = self.UTILS.element.getElement(DOM.Messages.cancel_edit_threads,
                                          "Cancel button")
        x.tap()
        self.UTILS.element.waitForElements(DOM.Messages.edit_threads_button,
                                           "Edit button")

    def threadEditModeON(self):
        """
        Turns on Edit mode while in the SMS threads screen.
        """
        edit_btn = self.UTILS.element.getElement(
            DOM.Messages.edit_threads_button, "Edit button")
        edit_btn.tap()
        self.UTILS.element.waitForElements(DOM.Messages.cancel_edit_threads,
                                           "Cancel button")

    def threadExists(self, num):
        """
        Verifies that a thread exists for this number (returns True or False).
        """
        boolOK = False
        try:
            self.parent.wait_for_element_present(
                "xpath", DOM.Messages.thread_selector_xpath.format(num), 1)
            boolOK = True
        except:
            boolOK = False

        return boolOK

    def threadType(self):
        """
        Returns the 'type' being used by this thread.
        """
        x = self.UTILS.element.getElement(DOM.Messages.type_and_carrier_field,
                                          "Type and carrier information")
        parts = x.text.split("|")
        typ = parts[0].strip()
        return typ if len(parts) > 1 else ''

    def time_of_last_message_in_thread(self):
        """
        Returns the time of the last message in the current thread.
        """
        t = self.UTILS.element.getElement(DOM.Messages.last_message_time,
                                          "Last message time")
        return t.text

    def time_of_thread(self, num):
        """
        Returns the time of a thread.
        """
        x = self.UTILS.element.getElement(
            ("xpath", DOM.Messages.thread_timestamp_xpath.format(num)),
            "Thread time", True, 5, False)
        return x.text

    def thread_timestamp(self, num):
        """
        Returns the timestamp of a thread
        """
        x = self.marionette.find_element(
            *DOM.Messages.last_message).get_attribute("data-timestamp")
        return float(x)

    def verify_mms_received(self, attached_type, sender_number):

        self.UTILS.iframe.switchToFrame(*DOM.Messages.frame_locator)
        self.openThread(sender_number)
        message = self.last_message_in_this_thread()
        self.UTILS.test.test(message,
                             "A received message appeared in the thread.",
                             True)

        self.UTILS.reporting.debug(
            "*** attached type: {}".format(attached_type))
        if attached_type == "img":
            elem = DOM.Messages.last_message_attachment_img
        elif attached_type == "video":
            elem = DOM.Messages.last_message_attachment_av
        elif attached_type == "audio":
            elem = DOM.Messages.last_message_attachment_av
        else:
            # self.UTILS.reporting.logResult("info", "incorrect value received")
            msg = "FAILED: Incorrect parameter received in verify_mms_received()"\
                ". Attached_type must be image, video or audio."
            self.UTILS.test.test(False, msg)

        self.UTILS.reporting.debug("*** searching for attachment type")
        # Look for all the attachments, since there can be more than one
        atts = self.UTILS.element.getElements(elem, "Last message attachments")
        self.UTILS.element.scroll_into_view(atts[0])
        found = False
        for att in atts:
            typ = att.get_attribute("data-attachment-type")
            self.UTILS.reporting.debug(
                "*** searching for attachment type Result: {}".format(typ))
            if typ == attached_type:
                found = True
        if not found:
            msg = "No attachment with type {} was found in the message".format(
                attached_type)
            self.UTILS.test.test(False, msg)

    def wait_for_message(self, send_time=None, timeout=120):
        """Wait for a received message in the current thread and return it.
        """
        if not send_time:
            send_time = self.last_sent_message_timestamp()

        poll_time = 2
        poll_reps = (timeout / poll_time)
        result = False

        for i in range(poll_reps):
            # Get last message in this thread.
            last_msg = self.last_message_in_this_thread()

            if not last_msg:
                time.sleep(poll_time)
                continue

            # If the send_time timestamp is greater than this message's timestamp,it means the message
            # we expect has not arrived yet, so we have to wait a bit more.
            message_data_time = float(
                last_msg.get_attribute("data-timestamp")) / 1000
            fmt = "data-timestamp of last message in thread: {:.3f} send_time: {:.3f} --> {}"
            self.UTILS.reporting.debug(
                fmt.format(message_data_time, send_time,
                           send_time > message_data_time))
            if send_time > message_data_time:
                continue

            # Is this a received message?
            if "incoming" in last_msg.get_attribute("class"):
                result = last_msg
                break

            # Nope - sleep then try again.
            time.sleep(poll_time)

        self.UTILS.test.test(
            result,
            "Last message in thread 'received' within {} seconds.".format(
                timeout))
        return result
Esempio n. 28
0
class test_main(GaiaTestCase):
    def setUp(self):
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        self.contact = MockContact(tel={
            'type': 'Mobile',
            'value': '123111111'
        })
        self.contact2 = MockContact(tel={
            'type': 'Mobile',
            'value': '123222222'
        })

        self.UTILS.general.insertContact(self.contact2)

    def tearDown(self):
        self.UTILS.general.remove_files()
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):
        # Store our picture on the device.
        self.UTILS.general.add_file_to_device(
            './tests/_resources/contact_face.jpg')

        # Create and verify contact
        self.contacts.launch()
        self.contacts.create_contact(self.contact, "gallery")
        self.contacts.verify_image_in_all_contacts(self.contact['name'])

        # Search for our contacts.
        self.contacts.search("test")
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"])

        # Verify that the image is present for the right contact.
        results_list = self.UTILS.element.getElements(
            DOM.Contacts.search_results_list, "Search results")
        tuples = zip(results_list, [self.contact, self.contact2],
                     [True, False])
        for t in tuples:
            ok = self.verify_img_for_contact(t[0], t[1], t[2])
            self.UTILS.test.test(
                ok, "Image was {}found (Expected: {})".format(
                    "" if ok else "not ", t[2]))

        screenshot = self.UTILS.debug.screenShotOnErr()
        self.UTILS.reporting.logResult("info", "Screenshot of search results",
                                       screenshot)

    def verify_img_for_contact(self, result, contact, expect_image):
        """Verify if an image is present for the result list item.

        The result item must be the specified by contact.
        Return True if the contact has a image and expected_image is True.
        False otherwise.
        """
        found = False
        if result.get_attribute("data-order") == contact["name"].replace(
                " ", "").upper():
            try:
                img = result.find_element("css selector", "li.contact-item[data-order*='{}'] span[data-type=img]".\
                                          format(contact['givenName']))
                if "blob" in img.get_attribute("data-src"):
                    found = True
            except:
                self.UTILS.reporting.logResult("info", "No image present for contact {} |"\
                                               " The image was indeed expected".format(result.text))
        else:
            self.UTILS.test.test(
                False, "This contact does not appear in the list: {}".format(
                    result.text))
        res = found == expect_image
        return res
Esempio n. 29
0
class test_main(GaiaTestCase):
    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.contact = MockContact()

        self.nameIncomplete = self.contact["givenName"][:4]
        self.surnameIncomplete = self.contact["familyName"][:2]

        name2 = self.nameIncomplete + "h"
        fname2 = self.surnameIncomplete + "t"

        self.contact2 = MockContact(givenName=name2, familyName=fname2)
        self.contact3 = MockContact(givenName='John', familyName='Smith')

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.general.insertContact(self.contact2)
        self.UTILS.general.insertContact(self.contact3)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # With nameIncomplete : Search for the sought contact.
        self.contacts.search(self.nameIncomplete)

        # With nameIncomplete: Verify our contact is listed.
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"])

        # With nameIncomplete: Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.contact3["givenName"], False)

        # Enter one more letter.
        self.UTILS.general.typeThis(DOM.Contacts.search_contact_input,
                                    "Search input",
                                    self.nameIncomplete +
                                    self.contact["givenName"][4],
                                    p_no_keyboard=True,
                                    p_validate=False,
                                    p_clear=False,
                                    p_enter=False)

        # Verify list updated.
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"], False)
        self.contacts.check_search_results(self.contact3["givenName"], False)

        # Cancel search.
        x = self.UTILS.element.getElement(DOM.Contacts.search_cancel_btn,
                                          "Search cancel button")
        x.tap()

        # With surnameIncomplete : Search for the sought contact.
        self.contacts.search(self.surnameIncomplete)

        # With surnameIncomplete: Verify our contact is listed.
        self.contacts.check_search_results(self.contact["familyName"])
        self.contacts.check_search_results(self.contact2["familyName"])

        # With surnameIncomplete: Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.contact3["familyName"], False)

        # Enter one more letter.
        self.UTILS.general.typeThis(DOM.Contacts.search_contact_input,
                                    "Search input",
                                    self.surnameIncomplete +
                                    self.contact["familyName"][2],
                                    p_no_keyboard=True,
                                    p_validate=False,
                                    p_clear=False,
                                    p_enter=False)

        # Verify list updated.
        self.contacts.check_search_results(self.contact["familyName"])
        self.contacts.check_search_results(self.contact2["familyName"], False)
        self.contacts.check_search_results(self.contact3["familyName"], False)
Esempio n. 30
0
class test_main(GaiaTestCase):

    def setUp(self):

        # Set up child objects...
        GaiaTestCase.setUp(self)
        self.UTILS = UTILS(self)
        self.contacts = Contacts(self)

        # Get details of our test contacts.
        self.contact = MockContact()

        self.nameIncomplete = self.contact["givenName"][:4]
        self.surnameIncomplete = self.contact["familyName"][:2]

        name2 = self.nameIncomplete + "h"
        fname2 = self.surnameIncomplete + "t"

        self.contact2 = MockContact(givenName=name2, familyName=fname2)
        self.contact3 = MockContact(givenName='John', familyName='Smith')

        self.UTILS.general.insertContact(self.contact)
        self.UTILS.general.insertContact(self.contact2)
        self.UTILS.general.insertContact(self.contact3)

    def tearDown(self):
        self.UTILS.reporting.reportResults()
        GaiaTestCase.tearDown(self)

    def test_run(self):

        # Launch contacts app.
        self.contacts.launch()

        # With nameIncomplete : Search for the sought contact.
        self.contacts.search(self.nameIncomplete)

        # With nameIncomplete: Verify our contact is listed.
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"])

        # With nameIncomplete: Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.contact3["givenName"], False)

        # Enter one more letter.
        self.UTILS.general.typeThis(DOM.Contacts.search_contact_input, "Search input", self.nameIncomplete + self.contact["givenName"][4],
                            p_no_keyboard=True, p_validate=False, p_clear=False, p_enter=False)

        # Verify list updated.
        self.contacts.check_search_results(self.contact["givenName"])
        self.contacts.check_search_results(self.contact2["givenName"], False)
        self.contacts.check_search_results(self.contact3["givenName"], False)

        # Cancel search.
        x = self.UTILS.element.getElement(DOM.Contacts.search_cancel_btn, "Search cancel button")
        x.tap()

        # With surnameIncomplete : Search for the sought contact.
        self.contacts.search(self.surnameIncomplete)

        # With surnameIncomplete: Verify our contact is listed.
        self.contacts.check_search_results(self.contact["familyName"])
        self.contacts.check_search_results(self.contact2["familyName"])

        # With surnameIncomplete: Verify the other contact is NOT listed.
        self.contacts.check_search_results(self.contact3["familyName"], False)

        # Enter one more letter.
        self.UTILS.general.typeThis(DOM.Contacts.search_contact_input, "Search input", self.surnameIncomplete + self.contact["familyName"][2],
                            p_no_keyboard=True, p_validate=False, p_clear=False, p_enter=False)

        # Verify list updated.
        self.contacts.check_search_results(self.contact["familyName"])
        self.contacts.check_search_results(self.contact2["familyName"], False)
        self.contacts.check_search_results(self.contact3["familyName"], False)