Giter Site home page Giter Site logo

eliasnogueira / selenium-java-lean-test-architecture Goto Github PK

View Code? Open in Web Editor NEW
489.0 30.0 166.0 34.57 MB

Ready to use Lean Test Automation Architecture using Java and Selenium WebDriver to speed up your test automation

License: MIT License

Java 100.00%
selenium-webdriver testng parallel java automated-testing

selenium-java-lean-test-architecture's Introduction

Lean Test Automation Architecture using Java and Selenium WebDriver

Actions Status

This project delivers to you a complete lean test architecture for your web tests using the best frameworks and practices.

It has a complete solution to run tests in different ways:

  • local testing using the browser on your local machine
  • parallel (or single) testing using Selenium Docker
  • local testing using TestContainers
  • Distributed execution using Selenium Grid

Examples

Local testing execution example

Local testing execution example

Parallel testing execution example with Selenium Grid

Parallel testing execution example with Selenium Grid

Languages and Frameworks

This project uses the following languages and frameworks:

Test architecture

We know that any automation project starts with a good test architecture.

This project can be your initial test architecture for a faster start. You will see the following items in this architecture:

Do you have any other items to add to this test architecture? Please do a pull request or open an issue to discuss.

Page Objects pattern

I will not explain the Page Object pattern because you can find a lot of good explanations and examples on the internet. Instead, I will explain what exactly about page objects I'm using in this project.

AbstractPageObject

This class has a protected constructor to remove the necessity to init the elements using the Page Factory. Also, it sets the timeout from the timeout property value located on general.properties file.

All the Page Object classes should extend the AbstractPageObject. It also tries to remove the driver object from the Page Object class as much as possible.

Important information

There's a NavigationPage on the common package inside the Page Objects. Notice that all the pages extend this one instead of the AbstractPageObject. I implemented this way:

  • because the previous and next buttons are fixed on the page (there's no refresh on the page)
  • to avoid creating or passing the new reference to the NavigationPage when we need to hit previous or next buttons

As much as possible avoid this strategy to not get an ElementNotFoundException or StaleElementReferenceException. Use this approach if you know that the page does not refresh.

Execution types

There are different execution types:

  • local
  • local-suite
  • selenium-grid
  • testcontainers

The TargetFactory class will resolve the target execution based on the target property value located on general.properties file. Its usage is placed on the BaseWeb class before each test execution.

Local execution

Local machine

This approach is automatically used when you run the test class in your IDE.

This execution type uses WebDriverManager class to instantiate the web browsers. When the target is local the createLocalDriver() method is used from the BrowserFactory class to return the browser instance.

The browser used in the test is placed on the browser property in the general.properties file.

Local Suite

This execution type also uses the WebDriverManager to instantiate the web browser. The difference is that the browser is taken from the TestNG suite file instead of the general.properties file, enabling you to run multi-browser test approach locally.

Testcontainers

This execution type uses the WebDriver Containers in Testcontainers to run the tests in your machine, but using the Selenium docker images for Chrome or Firefox.

When the target is testcontainers the TargetFactory uses the createTestContainersInstance() method to initialize the container based on the browser set in the browser property. Currently, Testcontainers only supports Chrome and Firefox.

Example

mvn test -Pweb-execution -Dtarget=testcontainers -Dbrowser=chrome

Remote execution

Selenium Grid

The Selenium Grid approach executes the tests in remote machines (local or remote/cloud grid). When the target is selenium-grid the getOptions method is used from the BrowserFactory to return the browser option class as the remote execution needs the browser capability.

The DriverFactory class has an internal method createRemoteInstance to return a RemoteWebDriver instance based on the browser capability.

You must pay attention to the two required information regarding the remote execution: the grid.url and grid.port property values on the grid.properties file. You must update these values before the start.

If you are using the docker-compose.yml file to start the Docker Selenium grid, the values on the grid.properties file should work.

You can take a look at the Execution with Docker Selenium Distributed to run the parallel tests using this example.

BrowserFactory class

This Factory class is a Java enum that has all implemented browsers to use during the test execution. Each browser is an enum, and each enum implements four methods:

  • createLocalDriver(): creates the browser instance for the local execution. The browser driver is automatically managed by the WebDriverManager library
  • createDriver(): creates the browser instance for the remote execution
  • getOptions(): creates a new browser Options setting some specific configurations, and it's used for the remote executions using the Selenium Grid
  • createTestContainerDriver() : Creates selenium grid lightweight test container in Standalone mode with Chrome/Firefox/Edge browser support.

You can see that the createLocalDriver() method use the getOptions() to get specific browser configurations, as starting the browser maximized and others.

The getOptions() is also used for the remote execution as it is a subclass of the AbstractDriverOptions and can be automatically accepted as either a Capabilities or MutableCapabilities class, which is required by the RemoteWebDriver class.

DriverManager class

The class DriverManager create a ThreadLocal for the WebDriver instance, to make sure there's no conflict when we run it in parallel.

BaseTest

This testing pattern was implemented on the BaseWeb class to automatically run the pre (setup) and post (teardown) conditions.

The pre-condition uses @BeforeMethod from TestNG creates the browser instance based on the values passed either local or remote execution. The post-condition uses @AfterMethod to close the browser instance. Both have the alwaysRun parameter as true to force the run on a pipeline.

Pay attention that it was designed to open a browser instance to each @Test located in the test class.

This class also has the TestListener annotation which is a custom TestNG listener, and will be described in the next section.

TestListener

The TestListener is a class that implements ITestListener. The following method is used to help logging errors and attach additional information to the test report:

  • onTestStart: add the browser information to the test report
  • onTestFailure: log the exceptions and add a screenshot to the test report
  • onTestSkipped: add the skipped test to the log

Logging

All the log is done by the Log4J using the @Log4j2 annotation.

The log4j2.properties has two strategies: console and file. A file with all the log information will be automatically created on the user folder with test_automation.log filename. If you want to change it, update the appender.file.fileName property value.

The log.error is used to log all the exceptions this architecture might throw. Use log.info or log.debug to log important information, like the users, automatically generated by the factory BookingDataFactory

Parallel execution

The parallel test execution is based on the parallel tests feature on TestNG. This is used by selenium-grid.xml test suite file which has the parallel="tests" attribute and value, whereas test item inside the test suite will execute in parallel. The browser in use for each test should be defined by a parameter, like:

<parameter name="browser" value="chrome"/>

You can define any parallel strategy.

It can be an excellent combination together with the grid strategy.

Execution with Docker Selenium Distributed

This project has the docker-compose.yml file to run the tests in a parallel way using Docker Selenium. To be able to run it in parallel the file has the Dynamic Grid Implementation that will start the container on demand.

This means that Docker Selenium will start a container test for a targeting browser.

Please note that you need to do the following actions before running it in parallel:

  • Docker installed
  • Pull the images for Chrome Edge and Firefox - Optional
    • Images are pulled if not available and initial test execution will be slow
      • docker pull selenium-standalog-chrome
      • docker pull selenium-standalog-firefox
      • docker pull selenium/standalone-edge
    • If you are using a MacBook with either M1 or M2 chip you must check the following experimental feature in Docker Desktop: Settings -> Features in development -> Use Rosetta for x86/amd64 emulation on Apple Silicon
  • Pay attention to the grid/config.toml file that has comments for each specific SO
  • Start the Grid by running the following command inside the grid folder
    • docker-compose up
  • Run the project using the following command
mvn test -Pweb-execution -Dsuite=selenium-grid -Dtarget=selenium-grid -Dheadless=true
  • Open the [Selenium Grid] page to see the node status

Configuration files

This project uses a library called Owner. You can find the class related to the property file reader in the following classes:

There are 3 properties (configuration) files located on src/test/java/resources/:

  • general.properties: general configuration as the target execution, browser, base url, timeout, and faker locale
  • grid.properties: url and port for the Selenium grid usage

The properties were divided into three different ones to better separate the responsibilities and enable the changes easy without having a lot of properties inside a single file.

Test Data Factory

Is the utilization of the Factory design pattern with the Fluent Builder to generate dynamic data. The BookingDataFactory has only one factory createBookingData returning a Booking object with dynamic data.

This dynamic data is generated by JavaFaker filling all the fields using the Build pattern. The Booking is the plain Java objects and the BookingBuilder is the builder class.

You can see the usage of the Builder pattern in the BookingDataFactory class.

Reading reference: https://reflectoring.io/objectmother-fluent-builder

Profiles executors on pom.xml

There is a profile called web-execution created to execute the test suite local.xml inside src/test/resources/suites folder. To execute this suite, via the command line you can call the parameter -P and the profile id.

Eg: executing the multi_browser suite

mvn test -Pweb-execution -Dtestng.dtd.http=true 

If you have more than one suite on src/test/resources/suites folder you can parameterize the xml file name. To do this you need:

  • Create a property on pom.xml called suite
<properties>
    <suite>local</suite>
</properties>
  • Change the profile id
<profile>
    <id>web-execution</id>
</profile>   
  • Replace the xml file name to ${suite} on the profile
<configuration>
    <suiteXmlFiles>
        <suiteXmlFile>src/test/resources/suites/${suite}.xml</suiteXmlFile>
    </suiteXmlFiles>
</configuration>
  • Use -Dsuite=suite_name to call the suite
mvn test -Pweb-execution -Dsuite=parallel

Pipeline as a code

The two files of the pipeline as a code are inside pipeline_as_code folder.

  • GitHub Actions to use it inside the GitHub located at .github\workflows
  • Jenkins: Jenkinsfile to be used on a Jenkins pipeline located at pipeline_as_code
  • GitLab CI: .gitlab-ci.yml to be used on a GitLab CI pipeline_as_code

selenium-java-lean-test-architecture's People

Contributors

bodiam avatar dependabot-preview[bot] avatar dependabot[bot] avatar eliasnogueira avatar henrique-barbase avatar mdiwakar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

selenium-java-lean-test-architecture's Issues

Face issue when use docker-compose up to run selenium grid

Hi,

I faced the issue that once run the selenium grid in docker, the node seems not run successfully. please refer to below logs.
Step to reproduce:

  1. Clone the repository to windows machine
  2. change the general.properties->target to remote
  3. change the pom.xml to parallel(no matter this step do or not will have the same issue)
  4. docker pull selenium/standalone-firefox:latest
  5. docker pull selenium/standalone-chrome:latest
  6. cd to grid
  7. execute "docker-compose up" in the powershell terminal

Observe the docker container for the node have below information(pay attention to the bottom lines):
2022-07-22 08:48:36,172 INFO Included extra file "/etc/supervisor/conf.d/selenium-grid-node-docker.conf" during parsing
2022-07-22 08:48:36,175 INFO supervisord started with pid 9
2022-07-22 08:48:37,177 INFO spawned: 'selenium-grid-node-docker' with pid 11
Starting Selenium Grid Node Docker...
2022-07-22 08:48:37,183 INFO success: selenium-grid-node-docker entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
08:48:37.535 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding
08:48:37.541 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing
08:48:37.631 INFO [UnboundZmqEventBus.] - Connecting to tcp://selenium-hub:4442 and tcp://selenium-hub:4443
08:48:37.682 INFO [UnboundZmqEventBus.] - Sockets created
08:48:38.685 INFO [UnboundZmqEventBus.] - Event bus ready
08:48:38.872 INFO [NodeServer.createHandlers] - Reporting self as: http://172.22.0.3:5555
08:48:38.902 INFO [NodeOptions.getSessionFactories] - Detected 8 available processors
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.openqa.selenium.grid.Bootstrap.runMain(Bootstrap.java:77)
at org.openqa.selenium.grid.Bootstrap.main(Bootstrap.java:70)
Caused by: org.openqa.selenium.grid.config.ConfigException: java.lang.reflect.InvocationTargetException
at org.openqa.selenium.grid.config.MemoizedConfig.getClass(MemoizedConfig.java:115)
at org.openqa.selenium.grid.node.config.NodeOptions.getNode(NodeOptions.java:131)
at org.openqa.selenium.grid.node.httpd.NodeServer.createHandlers(NodeServer.java:128)
at org.openqa.selenium.grid.node.httpd.NodeServer.asServer(NodeServer.java:184)
at org.openqa.selenium.grid.node.httpd.NodeServer.execute(NodeServer.java:231)
at org.openqa.selenium.grid.TemplateGridCommand.lambda$configure$4(TemplateGridCommand.java:129)
at org.openqa.selenium.grid.Main.launch(Main.java:83)
at org.openqa.selenium.grid.Main.go(Main.java:57)
at org.openqa.selenium.grid.Main.main(Main.java:42)
... 6 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.openqa.selenium.grid.config.ClassCreation.callCreateMethod(ClassCreation.java:50)
at org.openqa.selenium.grid.config.MemoizedConfig.lambda$getClass$4(MemoizedConfig.java:100)
at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1737)
at org.openqa.selenium.grid.config.MemoizedConfig.getClass(MemoizedConfig.java:95)
... 14 more
Caused by: org.openqa.selenium.docker.DockerException: Unable to reach the Docker daemon at http://host.docker.internal:2375
at org.openqa.selenium.grid.node.docker.DockerOptions.getDockerSessionFactories(DockerOptions.java:125)
at org.openqa.selenium.grid.node.local.LocalNodeFactory.create(LocalNodeFactory.java:80)
... 22 more
Exception in thread "Thread-0" java.lang.NullPointerException
at org.openqa.selenium.grid.node.httpd.NodeServer.lambda$new$0(NodeServer.java:80)
at java.base/java.lang.Thread.run(Thread.java:829)
2022-07-22 08:48:52,160 INFO exited: selenium-grid-node-docker (exit status 1; not expected)

could you please help to have a look if there is anything I need to configure?

Thanks a lot.

cannot attach the screenshot to the allure report

When I run "mvn clean test", there is a Error generated with below information:
"[TestNG-tests-1] AllureLifecycle - Could not add attachment: no test is running", this make the attachment missing from the allure report.

Could you please help on this?

Please upgrade to Datafaker

Javafaker has some security issues and is no longer maintained, and Datafaker is an actively maintained alterative.

About the selenium grid parallel limitation

Hi,

This is not an issue but a concern. Could you please let me know how to configure the count of one docker node support instance?

Currently based on some test, one node can support 8 docker instance to run, is this configurable or not?

Thanks.

Add Firefox and MicrosoftEdge execution on test container

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
Test container class just takes chrome as parameter, refactor the TargetFactory.java class to support Firefox and MicrosoftEdge browsers

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.