连接stf跑脚本

相关内容出处:https://github.com/email2vimalraj/appium-stf-example

DeviceApi.class

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.sun.xml.internal.ws.spi.db.BindingContextFactory.LOGGER;
import static io.restassured.RestAssured.given;

public class DeviceApi {
    private RequestSpecification specification;

    private static Logger logger = LoggerFactory.getLogger(DeviceApi.class);

    public DeviceApi(String baseUrl, String token) {
        specification = new RequestSpecBuilder()
                .setContentType("Application/json")
                .addHeader("Authorization", "Bearer " + token)
                .setBaseUri(baseUrl)
                .build();
    }

    public boolean connectDevice(String deviceSerial) {
        Response response = given().spec(specification)
                .get("/devices/" + deviceSerial).prettyPeek();
        JSONObject jsonObject = JSON.parseObject(response.asString());

        logger.info(isDeviceFound(jsonObject) + "");
        if (isDeviceFound(jsonObject)) {
            return false;
        }

        JSONObject deviceObject = jsonObject.getJSONObject("device");
        boolean present = deviceObject.getBooleanValue("present");
        boolean ready = deviceObject.getBooleanValue("ready");
        boolean using = deviceObject.getBooleanValue("using");
        Object ownerElement = deviceObject.get("owner");
        boolean owner = null != ownerElement;

        if (!present || !ready || using || owner) {
            logger.error("Device is in use");
            return false;
        }

        return addDeviceToUser(deviceSerial);
    }

    private boolean isDeviceFound(JSONObject jsonObject) {
        if (jsonObject.getString("success").equals("true")) {
            return true;
        }else {
            logger.error("device not found");
        }

        return false;
    }

    private boolean addDeviceToUser(String deviceSerial) {
        String requestBody = "{\"serial\": \"" + deviceSerial + "\"}";

        Response response = given().spec(specification)
                .body(JSON.toJSON(requestBody))
                .post("/user/devices");

        JSONObject jsonObject = JSON.parseObject(response.asString());

        if (!isDeviceFound(jsonObject)) {
            return false;
        }

        LOGGER.info("The device <" + deviceSerial + "> is locked successfully");
        return true;
    }

    public boolean releaseDevice(String deviceSerial) {
        Response response = given().spec(specification)
                .delete("/user/devices/" + deviceSerial).prettyPeek();

        JSONObject jsonObject = JSON.parseObject(response.asString());

        if (isDeviceFound(jsonObject)) {
            return false;
        }

        logger.info("The device <" + deviceSerial + "> is released successfully");
        return true;
    }
}

AndroidSTFDemo.class

import com.jane.DeviceApi;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URISyntaxException;

public class AndroidSTFDemo  {
    private static final String STF_SERVICE_URL = "your-host:port/api/v1";  // Change this URL
    private static final String ACCESS_TOKEN = "your-access-token";  // Change this access token

    private AndroidDriver androidDriver;
    private String deviceSerial = "your-serial";
    private AppiumDriverLocalService service;
    private DeviceApi deviceApi;

    private void connectToStfDevice() throws MalformedURLException, URISyntaxException {
        this.deviceApi = new DeviceApi(STF_SERVICE_URL,ACCESS_TOKEN);
        this.deviceApi.connectDevice(this.deviceSerial);
    }

    private void createAppiumService() {
        this.service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder().withIPAddress("127.0.0.1"));
        this.service.start();
    }

    @BeforeClass
    public void setup() throws MalformedURLException, URISyntaxException {
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "ANDROID");
        desiredCapabilities.setCapability(CapabilityType.PLATFORM, "ANDROID");
        desiredCapabilities.setCapability("udid", "your-serial");
        desiredCapabilities.setCapability("appPackage", "your-app-package-name");
        desiredCapabilities.setCapability("appActivity", "your-activity-name");

        connectToStfDevice();
        createAppiumService();

        androidDriver = new AndroidDriver(this.service.getUrl(), desiredCapabilities);
    }

    @AfterClass
    public void tearDown() {
        if (androidDriver != null) {
            androidDriver.quit();
        }

        if (this.service.isRunning()) {
            this.service.stop();
            this.deviceApi.releaseDevice(this.deviceSerial);
        }
    }

    @Test
    public void currentActivityTest() throws InterruptedException {
        Assert.assertEquals(androidDriver.currentActivity(), "xxx", "Activity not match");
    }
}

可以运行啦。。。

你可能感兴趣的:(连接stf跑脚本)