Apache ANT с Selenium: Пълен урок
Какво е Apache Ant?
Докато създавате цялостен софтуерен продукт, трябва да се погрижите за различни API на трети страни, техния класов път, почистване на предишни изпълними двоични файлове, компилиране на нашия изходен код, изпълнение на изходния код, създаване на отчети и кодова база за внедряване и т.н. Ако тези задачи са извършвани един по един ръчно, това ще отнеме огромно време и процесът ще бъде податлив на грешки.
Тук идва значението на инструмент за изграждане като Ant. Той съхранява, изпълнява и автоматизира всички процеси в последователен ред, споменат в конфигурационния файл на Ant (обикновено build.xml).
Полза от Ant build
- Ant създава жизнения цикъл на приложението, т.е. почиства, компилира, задава зависимост, изпълнява, докладва и т.н.
- Зависимостта на API на трета страна може да бъде зададена от Ant, т.е. пътят на класа на друг Jar файл се задава от файла за изграждане на Ant.
- Създава се пълно приложение за доставка и внедряване от край до край.
- Това е прост инструмент за изграждане, при който всички конфигурации могат да бъдат направени с помощта на XML файл и който може да се изпълни от командния ред.
- Това прави вашия код чист, тъй като конфигурацията е отделна от действителната логика на приложението.
Как да инсталирате Ant
Стъпки за инсталиране на Ant Windows е както следва
Стъпка 1) Отиди https://ant.apache.org/bindownload.cgi Или изтеглете .zip файл от apache-ant-1.9.4-bin.zip
Стъпка 2) Разархивирайте папката и отидете на и копирайте пътя до корена на разархивираната папка
Стъпка 3) Отидете на Старт -> Компютър -> щракнете с десния бутон тук и изберете „Свойства“, след което щракнете върху Разширени системни настройки
Стъпка 4) Отваря се нов прозорец. Кликнете върху бутона „Променлива на средата…“.
Стъпка 5) Щракнете върху бутона „Ново…“ и задайте име на променлива като „ANT_HOME“ и стойност на променливата като главна пътека към разархивирана папка и щракнете върху OK.
Стъпка 6) сега изберете променлива „Path“ от списъка и щракнете върху „Edit“ и добавете; %ANT_HOME%\bin.
Рестартирайте системата веднъж и сте готови да използвате инструмента за изграждане на Ant сега.
Стъпка 7) За да проверите версията на вашия Ant чрез командния ред:
Ant – версия
Разбиране на Build.xml
Build.xml е най-важният компонент на инструмента за изграждане на Ant. За а Java проект, всички задачи, свързани с почистване, настройка, компилация и внедряване, са споменати в този файл в XML формат. Когато изпълним този XML файл с помощта на командния ред или който и да е IDE плъгин, всички инструкции, записани в този файл, ще бъдат изпълнени по последователен начин.
Нека разберем кода в примерен build.XML
-
Етикетът на проекта се използва за споменаване на име на проект и атрибут на basedir. Basedir е основната директория на приложението
<project name="YTMonetize" basedir=".">
- Таговете на свойствата се използват като променливи във файла build.XML, за да се използват в следващите стъпки
<property name="build.dir" value="${basedir}/build"/>
<property name="external.jars" value=".\resources"/>
<property name="ytoperation.dir" value="${external.jars}/YTOperation"/>
<property name="src.dir"value="${basedir}/src"/>
- Target тагове, използвани като стъпки, които ще се изпълняват в последователен ред. Атрибутът Name е името на целта. Можете да имате няколко цели в един build.xml
<target name="setClassPath">
- пътят се използва за логическо групиране на всички файлове, които са в общо местоположение
<path id="classpath_jars">
- pathelement ще зададе пътя до корена на общото местоположение, където се съхраняват всички файлове
<pathelement path="${basedir}/"/> - pathconvert таг, използван за преобразуване на пътеки на всички общи файлове вътре в path таг във формат на classpath на системата
<pathconvert pathsep=";" property="test.classpath" refid="classpath_jars"/>
- таг за набор от файлове, използван за задаване на classpath за различен jar на трета страна в нашия проект
<fileset dir="${ytoperation.dir}" includes="*.jar"/> - Ехо етикетът се използва за отпечатване на текст на конзолата
<echo message="deleting existing build directory"/>
- Изтриването на етикет ще изчисти данните от дадена папка
<delete dir="${build.dir}"/>
- mkdir ще създаде нова директория
<mkdir dir="${build.dir}"/>
- javac таг, използван за компилиране на изходния код на Java и преместване на .class файлове в нова папка
<javac destdir="${build.dir}" srcdir="${src.dir}">
<classpath refid="classpath_jars"/>
</javac>
- jar ще създаде jar файл от .class файлове
<jar destfile="${ytoperation.dir}/YTOperation.jar" basedir="${build.dir}">
- манифестният маркер ще зададе основния ви клас за изпълнение
<manifest> <attribute name="Main-Class" value="test.Main"/> </manifest>
- атрибут 'depends', използван, за да направи една цел зависима от друга цел
<target name="run" depends="compile">
- java таг ще изпълни основната функция от буркана, създаден в целевата секция за компилиране
<java jar="${ytoperation.dir}/YTOperation.jar" fork="true"/>
Стартирайте Ant с помощта на Eclipse плъгин
За да стартирате Ant от eclipse, отидете на build.xml файл -> щракнете с десния бутон върху файла -> Изпълни като… -> щракнете върху Build файл
Пример
Ще вземем малка примерна програма, която ще обясни функционалността на Ant много ясно. Структурата на нашия проект ще изглежда така –
Тук в този пример имаме 4 цели
- Задайте път на класа за външни буркани,
- Изчистете вече изпълнения код
- Компилирайте съществуващ java код
- Стартирайте кода
Guru99AntClass.class
package testAnt;
import java.util.Date;
public class Guru99AntClass {
public static void main(String...s){
System.out.println("HELLO GURU99 ANT PROGRAM");
System.out.println("TODAY's DATE IS->"+ currentDate() );
}
public static String currentDate(){
return new Date().toString();
}
}
Build.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->
<project name="YTMonetize" basedir=".">
<!--Property tags will be used as variables in build.xml file to use in further steps-->
<property name="build.dir" value="${basedir}/build"/>
<property name="external.jars" value=".\resources"/>
<property name="ytoperation.dir" value="${external.jars}/YTOperation"/>
<property name="src.dir"value="${basedir}/src"/>
<!--Target tags used as steps that will execute in sequential order. name attribute will be the name of the target and < a name=OLE_LINK1 >'depends' attribute used to make one target to depend on another target -->
<target name="setClassPath">
<path id="classpath_jars">
<pathelement path="${basedir}/"/>
</path>
<pathconvert pathsep=";"property="test.classpath" refid="classpath_jars"/>
</target>
<target name="clean">
<!--echo tag will use to print text on console-->
<echo message="deleting existing build directory"/>
<!--delete tag will clean data from given folder-->
<delete dir="${build.dir}"/>
</target>
<target name="compile" depends="clean,setClassPath">
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--mkdir tag will create new director-->
<mkdir dir="${build.dir}"/>
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--javac tag used to compile java source code and move .class files to a new folder-->
<javac destdir="${build.dir}" srcdir="${src.dir}">
<classpath refid="classpath_jars"/>
</javac>
<!--jar tag will create jar file from .class files-->
<jar destfile="${ytoperation.dir}/YTOperation.jar"basedir="${build.dir}">
<!--manifest tag will set your main class for execution-->
<manifest>
<attribute name="Main-Class" value="testAnt.Guru99AntClass"/>
</manifest>
</jar>
</target>
<target name="run" depends="compile">
<!--java tag will execute main function from the jar created in compile target section-->
<java jar="${ytoperation.dir}/YTOperation.jar"fork="true"/>
</target>
</project>
Как да изпълним TestNG код с помощта на Ant
Тук ще създадем клас с Testng методи и задайте пътя на класа за Тестване в build.xml.
Сега, за да изпълним метода testng, ще създадем друг файл testng.xml и ще извикаме този файл от файла build.xml.
Стъпка 1) Ние създаваме a "Guru99AntClass.клас“ в опаковка testAnt
Guru99AntClass.class
package testAnt;
import java.util.Date;
import org.testng.annotations.Test;
public class Guru99AntClass {
@Test
public void Guru99AntTestNGMethod(){
System.out.println("HELLO GURU99 ANT PROGRAM");
System.out.println("TODAY's DATE IS->"+ currentDate() );
}
public static String currentDate(){
return new Date().toString();
}
}
Стъпка 2) Създайте цел за зареждане на този клас в Build.xml
<!-- Load testNG and add to the class path of application -->
<target name="loadTestNG" depends="setClassPath">
<!—using taskdef tag we can add a task to run on the current project. In below line, we are adding testing task in this project. Using testing task here now we can run testing code using the ant script -->
<taskdef resource="testngtasks" classpath="${test.classpath}"/>
</target>
Стъпка 3) Създайте testng.xml
testng.xml
<?xml version="1.0"encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="YT"thread-count="1"> <test name="GURU99TestNGAnt"> <classes> <class name="testAnt.Guru99AntClass"> </class> </classes> </test> </suite>
Стъпка 4) Създаване на Target в Build.xml, за да стартирате това TestNG код
<target name="runGuru99TestNGAnt" depends="compile">
<!-- testng tag will be used to execute testng code using corresponding testng.xml file. Here classpath attribute is setting classpath for testng's jar to the project-->
<testng classpath="${test.classpath};${build.dir}">
<!—xmlfileset tag is used here to run testng's code using testing.xml file. Using includes tag we are mentioning path to testing.xml file-->
<xmlfileset dir="${basedir}" includes="testng.xml"/>
</testng>
Стъпка 5) Пълният Build.xml
<?xml version="1.0"encoding="UTF-8"standalone="no"?>
<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->
<project name="YTMonetize" basedir=".">
<!--Property tags will be used as variables in build.xml file to use in further steps-->
<property name="build.dir"value="${basedir}/build"/>
<!-- put testng related jar in the resource folder -->
<property name="external.jars" value=".\resource"/>
<property name="src.dir" value="${basedir}/src"/>
<!--Target tags used as steps that will execute in sequential order. name attribute will be the name
of the target and 'depends' attribute used to make one target to depend on another target-->
<!-- Load testNG and add to the class path of application -->
<target name="loadTestNG"depends="setClassPath">
<taskdef resource="testngtasks"classpath="${test.classpath}"/>
</target>
<target name="setClassPath">
<path id="classpath_jars">
<pathelement path="${basedir}/"/>
<fileset dir="${external.jars}" includes="*.jar"/>
</path>
<pathconvert pathsep=";"property="test.classpath"refid="classpath_jars"/>
</target>
<target name="clean">
<!--echo tag will use to print text on console-->
<echo message="deleting existing build directory"/>
<!--delete tag will clean data from given folder-->
<delete dir="${build.dir}"/>
</target>
<target name="compile"depends="clean,setClassPath,loadTestNG">
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--mkdir tag will create new director-->
<mkdir dir="${build.dir}"/>
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--javac tag used to compile java source code and move .class files to a new folder-->
<javac destdir="${build.dir}"srcdir="${src.dir}">
<classpath refid="classpath_jars"/>
</javac>
</target>
<target name="runGuru99TestNGAnt"depends="compile">
<!-- testng tag will be used to execute testng code using corresponding testng.xml file -->
<testng classpath="${test.classpath};${build.dir}">
<xmlfileset dir="${basedir}"includes="testng.xml"/>
</testng>
</target>
</project>
Стъпка 6) Продукция
Мравка с Selenium Уебдрайвер
Досега сме научили, че с помощта на ANT можем да поставим всички буркани на трети страни на определено място в системата и да зададем техния път за нашия проект. Използвайки този метод, ние настройваме всички зависимости на нашия проект на едно място и го правим по-надежден за компилиране, изпълнение и внедряване.
По същия начин, за нашите проекти за тестване, използващи селен, можем лесно да споменем зависимостта от селен в build.xml и не е необходимо да добавяме ръчно клас път към него в нашето приложение.
Така че сега можете да игнорирате споменатия по-долу традиционен начин за задаване на пътеки към класове за проекта.
Пример:
Ще модифицираме предишния пример
Стъпка 1) Задайте свойството selenium.jars на свързан със селен jar в папката с ресурси
<property name="selenium.jars" value=".\selenium"/>
Стъпка 2) В целевия setClassPath добавете файловете със селен
<target name="setClassPath">
<path id="classpath_jars">
<pathelement path="${basedir}/"/>
<fileset dir="${external.jars}" includes="*.jar"/>
<!-- selenium jar added here -->
<fileset dir="${selenium.jars}" includes="*.jar"/>
</path>
Стъпка 3) Пълен Build.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->
<project name="YTMonetize" basedir=".">
<!--Property tags will be used as variables in build.xml file to use in further steps-->
<property name="build.dir" value="${basedir}/build"/>
<!-- put testng related jar in the resource folder -->
<property name="external.jars" value=".\resource"/>
<!-- put selenium related jar in resource folder -->
<property name="selenium.jars" value=".\selenium"/>
<property name="src.dir" value="${basedir}/src"/>
<!--Target tags used as steps that will execute in sequential order. name attribute will be the name
of the target and 'depends' attribute used to make one target to depend on another target-->
<!-- Load testNG and add to the class path of application -->
<target name="loadTestNG" depends="setClassPath">
<taskdef resource="testngtasks" classpath="${test.classpath}"/>
</target>
<target name="setClassPath">
<path id="classpath_jars">
<pathelement path="${basedir}/"/>
<fileset dir="${external.jars}" includes="*.jar"/>
<!-- selenium jar added here -->
<fileset dir="${selenium.jars}"includes="*.jar"/>
</path>
<pathconvert pathsep=";" property="test.classpath" refid="classpath_jars"/>
</target>
<target name="clean">
<!--echo tag will use to print text on console-->
<echo message="deleting existing build directory"/>
<!--delete tag will clean data from given folder-->
<delete dir="${build.dir}"/>
</target>
<target name="compile" depends="clean,setClassPath,loadTestNG">
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--mkdir tag will create new director-->
<mkdir dir="${build.dir}"/>
<echo message="classpath:${test.classpath}"/>
<echo message="compiling.........."/>
<!--javac tag used to compile java source code and move .class files to new folder-->
<javac destdir="${build.dir}"srcdir="${src.dir}">
<classpath refid="classpath_jars"/>
</javac>
</target>
<target name="runGuru99TestNGAnt" depends="compile">
<!-- testng tag will be used to execute testng code using corresponding testng.xml file -->
<testng classpath="${test.classpath};${build.dir}">
<xmlfileset dir="${basedir}" includes="testng.xml"/>
</testng>
</target>
</project>
Стъпка 4) Сега променете предварително създадения клас Guru99AntClass.java с нов код.
Тук в този пример нашите стъпки използват Selenium са:
- Отиди https://demo.guru99.com/test/guru99home/
- Прочетете всички връзки към курсовете един по един
- Отпечатайте хипервръзка на всички курсове на конзолата.
Guru99AntClass.java:
package testAnt;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class Guru99AntClass {
@Test
public void Guru99AntTestNGMethod(){
WebDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/test/guru99home/");
List<WebElement> listAllCourseLinks = driver.findElements(By.xpath("//div[@class='canvas-middle']//a"));
for(WebElement webElement : listAllCourseLinks) {
System.out.println(webElement.getAttribute("href"));
}
}
}
Стъпка 5) След успешно изпълнение изходът ще изглежда така:
Изтеглете примерния файл по-горе
Oбобщение
Ant е инструмент за изграждане на Java.
Ant, използван за компилиране на код, внедряване, процес на изпълнение.
Ant може да бъде изтеглен от Apache уебсайта.
Build.xml файл, използван за конфигуриране на цели за изпълнение с помощта на Ant.
Ant може да се стартира от командния ред или подходящ IDE плъгин като eclipse.















