Appium taking screenshots for failures

714 views Asked by At

I'm building android framework using Appium, Serenity and POM model.

I wanna take screenshots if any of the steps failed.

Can anybody help me with code and please let me know where to put that? Eg I have Pages, steps and stepdefinition class. Not sure where to implement that?

2

There are 2 answers

2
Mikhail Barinov On

I tried to compare pictures with template by OpenCV library. That's what I do:

  1. Add method to base_page.py.

    def compare_image_with_screenshot(self, image_name: str):
        os.chdir('../src/screenshots/')
    
        with open(f'{image_name}.png', 'rb') as img:
            first_image = base64.b64encode(img.read()).decode('ascii')
    
        second_image = base64.b64encode(self._driver.get_screenshot_as_png()).decode('ascii')
    
        return self._driver.get_images_similarity(first_image, second_image)
    
  2. Use this method in Page Object file.

    @allure.step('Compare screenshot with template')
    def get_image_comparison_percents(self):
    """
    This method gets screenshot on device with template in repo. Comparison result is percentage of similarity. Test is OK if comparison more than 90%
    """
        result = self.compare_image_with_screenshot(OfflineLocators.offline_stub)
        return result.get('score')
    
  3. Use step in necessary test.

    @allure.link(url='https://jira.myproject.tech/browse/TEST-1', name='TEST-1 - Offline stub')
    @allure.title('Offline stub')
    def test_offline_stub(appdriver):
    
        TourActions(appdriver).skip_tour()
        Navigation(appdriver).open_my_offline_page()
    
        assert Offline(appdriver).get_page_title_text() == 'Offline'
        assert Offline(appdriver).get_image_comparison_percents() > 0.9
    

In result of all of this I get some percentage of pictures similarity. It can be with that percentage what you need. For my tests it is OK.

If you mean screenshots for the test results, just let me know and I can show you example how I did it with Allure.

If you mean usual screenshots in Appium, please provide some mistakes which you catch.

0
Mikhail Barinov On

Below is example to get video if test is failed.

  1. conftest.py (in the root directory)

    @pytest.fixture
    def appdriver():
    
    driver = config.get_driver_caps()
    
    if config.IS_IOS:
        driver.start_recording_screen(videoQuality='high', videoType='mpeg4', videoFps='24')
    else:
        driver.start_recording_screen()
    
    yield driver
    
    attach_device_log(driver)
    save_screenshot(driver)
    driver.quit()
    
  2. Save screenshot method

    def save_screenshot(appdriver):
        allure.attach(
             appdriver.get_screenshot_as_png(),
             name='screenshot',
             attachment_type=allure.attachment_type.PNG
         )