Run tests with Biometric authentication

Below you can find information on how to run tests, which include Biometric authentication steps

Prerequisites

  • Existing native application with the Biometric authentication.
  • The app is installed on a device with image injection enabled.
    More details can be found here and in our API reference collection.
  • The tests can operate with system alerts
    For example, using the Appium command.
  • Access key is generated.

Step 1: Add executing of the Biometric authentication API

We have the specific API action for the Biometric authentication in our public API.
The action contains only one boolean parameter, which relates to the authentication result (success or fail)
Below you can find an example for popular programming languages.

 // Rest-assured library is using here https://rest-assured.io/
 
   public void submitBioAuthResult(String serial, boolean isSuccess) {
        JsonObject object = new JsonObject();
        object.addProperty("touchValid", isSuccess);
        RestAssured.given().
                contentType(ContentType.JSON).
                baseUri("https://app.mobitru.com/billing/unit/"+
                      <TEAM_ACCOUNT_NAME>
                      +"/automation/api").
                auth().oauth2(<ACCESS_KEY>).
                when().
                body(object.toString()).
                post("device/{serial}/injection/touch", serial).
                then().
                statusCode(HTTP_NO_CONTENT);
    }
const axios = require('axios');
const KEY = 'mobitru_ak_....';
const PROJECT_NAME = '<TEAM_CODE>';
const APPIUM_HUB = 'app.mobitru.com';

async function submitBioAuthResult(isSuccess) {
    // extract device serial from capabilities and build an API url
    const serial = browser.options.capabilities["appium:udid"];
    const url = `https://${APPIUM_HUB}/billing/unit/${PROJECT_NAME}/automation/api/device/${serial}/injection/touch`;
    const headers = {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${KEY}`
    };
    const payload = {
        "touchValid": isSuccess
    };

    axios.post(url, payload, { headers })
        .then(response => {
            if (response.status === 204) {
                console.log("Submitting Bio Auth was successful with HTTP 204 No Content.");
            } else {
                console.log(`Unexpected status code: ${response.status}`);
            }
        });
}
import requests

PROJECT_NAME = "<TEAM_CODE>"
ACCESS_KEY = "mobitru_ak_...."
APPIUM_HUB = "app.mobitru.com"
DEVICE_UDID = "<DEVICE_SERIAL>"

def submit_bio_auth_result(is_success):
    url = f"https://{APPIUM_HUB}/billing/unit/{PROJECT_NAME}/automation/api/device/{DEVICE_UDID}/injection/touch"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {ACCESS_KEY}",
    }
    payload = {
        "touchValid": is_success
    }

    response = requests.post(url, json=payload, headers=headers)

    if response.status_code == 204:
        print("Request was successful with HTTP 204 No Content.")
    else:
        print(f"Failed to submit bio auth. Status code: {response.status_code}, Response: {response.text}")
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;

....

      const string ProjectName = "<TEAM_CODE>";
      const string AccessKey = "mobitru_ak_....";
      const string AppiumHost = "app.mobitru.com";
      const string DeviceUdid = "<DEVICE_SERIAL>";


private void SubmitBioAuthResult(bool isSuccess)
        {
            // API URL
            string apiUrl = $"https://{AppiumHost}/billing/unit/{ProjectName}/automation/api/device/{DeviceUdid}/injection/touch";

            using (var httpClient = new HttpClient())
            {
                // Headers
                var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessKey);

                // Define payload
                var payload = new
                {
                    touchValid = isSuccess
                };
                // Serialize payload to JSON
                var payloadJson = System.Text.Json.JsonSerializer.Serialize(payload);

                // Add content type header
                request.Content = new StringContent(payloadJson, Encoding.UTF8, "application/json");

                // Send POST request (synchronous)

                var response = httpClient.Send(request);

                // Handle response
                if (response.IsSuccessStatusCode && response.StatusCode == System.Net.HttpStatusCode.NoContent)
                {
                    Console.WriteLine("Submitting Bio Auth was successful");
                }
                else
                {
                    Console.WriteLine($"Failed to submit Bio Auth. Status code: {(int)response.StatusCode}, Response: {response.Content.ReadAsStringAsync().Result}");
                }
            }
        }

Step 2: Cover the Biometric authentication pop-up

The Mobitru injects a specific pop-up while installing the App.
The pop-up activates when the App is requesting the authentication confirm.
Also, here is an example of the pop-up wait for Appium:

 // Rest-assured library is using here https://rest-assured.io/
 
public void startLoginViaBio() {
        // example of trigger the biometric authentication process
        signInBioButton.click();
        // wait for the pop-up
        new WebDriverWait(driver, Duration.ofSeconds(30), Duration.ofSeconds(1)).
                ignoring(WebDriverException.class).
                until(ExpectedConditions.alertIsPresent());
}
// The example is for WebdriverIO framework

async function startLoginViaBio() {

    // Activate bio auth
    const bioLoginXPath = browser.isAndroid
        ? "//*[@resource-id='com.epam.mobitru:id/login_bio']" // Android XPath
        : "//XCUIElementTypeButton[starts-with(@name,'Biometric authentication')]"; // iOS XPath

    const bioLoginElement = await driver.$(bioLoginXPath);
    await bioLoginElement.click();

    await driver.waitUntil(
        async () => (await driver.getAlertText()) !== null,
        {timeout: DEFAULT_WAIT_TIMEOUT_MS, timeoutMsg: "Alert not found"}
    );
}
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def start_login_via_bio(driver):
    is_android = "android" == driver.capabilities.get("platformName").lower()

    # activate bio auth
    activate_xpath = "//*[@resource-id='com.epam.mobitru:id/login_bio']" if is_android else "//XCUIElementTypeButton[starts-with(@name,'Biometric authentication')]"
    driver.find_element(AppiumBy.XPATH,activate_xpath).click()

    WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT_SEC).until(
        EC.alert_is_present()
    )
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Support.UI;


       private void StartLoginViaBio()
        {
            bool isAndroid = driver.PlatformName.ToLower().Equals("android");
            // XPath for element activation
            string bioLoginXPath = isAndroid
                ? "//*[@resource-id='com.epam.mobitru:id/login_bio']"
                : "//XCUIElementTypeButton[starts-with(@name,'Biometric authentication')]";

            // Find and click the element
            AppiumElement bioLoginElement = driver.FindElement(By.XPath(bioLoginXPath));
            bioLoginElement.Click();
            WebDriverWait wait = new(driver, TimeSpan.FromSeconds(DefaultWaitTimeoutSec));
            wait.Until(driver => !string.IsNullOrEmpty(driver.SwitchTo().Alert().Text));
        }

Step 3: Use both actions in a test

In the end, you can cover the full scenario by using both actions one after another.
Below you can find an example for popular programming languages:

   @Test(description = "Check login with biometric auth")
    public void loginValidBio() {
        startLoginViaBio();
        submitBioAuthResult(udid, true);
        //steps afrer success login...
    }
// The example is for WebdriverIO framework

describe('Appium Bio Auth Test', () => {

    it('should successfully logged using Bio Auth', async () => {

        // trigger the auth via Bio
        await startLoginViaBio();

        // submit auth via bio
        await submitBioAuthResult(true)

        //wait for the element, which appears after success auth
        const resultXpath = browser.isAndroid
            ? "//*[@resource-id='com.epam.mobitru:id/category']" // Android XPath
            : "//*[starts-with(@name,'productHeaderViewLabel')]"; // iOS XPath
        const resultElement = await $(resultXpath);
        await resultElement.waitForDisplayed({timeout: DEFAULT_WAIT_TIMEOUT_MS});
    });

});
import pytest

def test_bio_auth(driver):

    # trigger the auth via Bio
    start_login_via_bio(driver)

    # submit auth via bio
    submit_bio_auth_result(True)

    # wait for the element, which appears after success auth
    is_android = "android" == driver.capabilities.get("platformName").lower()
    result_xpath = "//*[@resource-id='com.epam.mobitru:id/category']" if is_android else "//*[starts-with(@name,'productHeaderViewLabel')]"
    WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT_SEC).until(
        EC.visibility_of_element_located((MobileBy.XPATH, result_xpath))
    )
using NUnit.Framework;


        [Test]
        public void TestQrCode()
        {
            // trigger the auth via Bio
            StartLoginViaBio();

            // submit auth via bio
            SubmitBioAuthResult(true);

            // wait for the element, which appears after success auth

            // Select the correct XPath based on the platform
            string resultXPath = driver.PlatformName.ToLower().Equals("android")
                ? "//*[@resource-id='com.epam.mobitru:id/category']"
                : "//*[starts-with(@name,'productHeaderViewLabel')]";

            // Wait for the element using WebDriverWait
            WebDriverWait wait = new(driver, TimeSpan.FromSeconds(DefaultWaitTimeoutSec));
            wait.Until(driver => driver.FindElement(By.XPath(resultXPath)).Displayed);
        }

Note:

If you don’t have an Application with Biometric authentication but would like to try the described steps, please use our open-source demo apps for Android and iOS.

Scroll to Top