Jul 17, 2023

Popular API/UI automation tools/frameworks (2023)

(copied some content from chat.openai.com :D)

API automation:

  • Postman(JS)/Newman: Postman is a widely used API development and testing tool that provides a user-friendly interface for designing, executing, and automating API tests. It offers features like test scripting, environment management, test data management, and integrations with other tools.
  • RestAssured(Java): RestAssured is a Java library for testing RESTful APIs. RestAssured supports all REST methods. It's widely used to test JSON and XML-based web applications. It provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. But consider Karate vs REST-assured for a new project.
  • SoapUI vs ReadyAPI: SoapUI is an open-source API testing tool specifically designed for testing SOAP and RESTful web services. It offers a comprehensive set of features for creating and executing functional, security, and performance tests.
  • JMeter(Java): Apache JMeter is primarily known for performance testing but also supports functional API testing. It can simulate high loads and stress test APIs, making it suitable for both functional and performance testing scenarios.

UI automation:

  • Selenium(Java, Python, C#, Ruby, JS, Kotlin): Selenium is an open-source automation framework widely used for automating web browsers and web application testing. The Selenium WebDriver is the core component of Selenium that provides a programming interface to interact with web browsers. It allows you to locate and manipulate web elements, handle browser navigation, and perform various actions required for testing.
  • Appium(JS, Python, Java, Ruby): Appium is a test automation tool for Android and iOS apps. Appium leverages the WebDriver protocol and shares a similar architecture with Selenium. It allows for code reuse and knowledge transfer between web and mobile automation.
API & UI: 
  • Playwright(Node.js, Python, Java, .NET): Playwright is an open-source JavaScript-based automation framework that enables developers and testers to automate web browser interactions across multiple browsers. It provides a high-level, user-friendly API that simplifies the process of browser automation. Playwright provides a JavaScript API for making HTTP requests, enabling you to send API requests, handle responses, and perform assertions. Playwright’s multi-browser support and cross-platform compatibility make it a versatile choice for API testing in a web context.
  • Cypress(JS): Cypress is a modern front-end testing tool built using JavaScript and focuses on making testing easier for developers and QA engineers. It uses a unique DOM manipulation technique and runs directly in the browser, providing a more developer-friendly approach to testing applications. It can also be used for API testing using its cy.request() command.
Macro Automation Framework: 
  • Karate(Java): Karate is an open-source API testing tool built on top of Cucumber and Gatling, a unified test automation platform combining API testing, API performance testing, API mocks & UI testing.
  • Robot Framework (Python): Robot Framework is an open-source test automation framework that is widely used for acceptance testing, robotic process automation (RPA), and acceptance test-driven development (ATDD). It provides a simple, readable syntax that enables easy test case creation and maintenance.
  • CodeceptJS(JS): CodeceptJS is an open-source JavaScript-based end-to-end testing framework that simplifies the process of writing and executing functional tests for web applications. It provides a high-level, human-readable API that abstracts away the complexities of underlying test automation tools like Selenium WebDriver or Puppeteer. CodeceptJS uses Helper modules to provide actions to I object. Currently, CodeceptJS has helpers for web testing(Playwright, WebDriver, Puppeteer, Protractor, TestCafe, Nightmare), mobile testing(Appium, Detox), API testing(REST, GraphQL) and AI(OpenAI).

Dec 13, 2019

Use puppeteer with waitUntil.networkidle0 to get fully loaded page

To solve 'Is there a way to let cURL wait until the page's dynamic updates are done?', here is the code to solve it after googlings:


const puppeteer = require('/usr/local/lib/node_modules/puppeteer');
const fs = require('fs');

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function getContent(url, outputFile) {
  const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
  const page = await browser.newPage();

  retries = 0

  while (retries < 3) {
    try {
      const response = await page.goto(url, {waitUntil: 'networkidle0'});
      const status = response._status
    
      if (status == '200') {
        const html = await page.content();
        fs.writeFile(outputFile, html, function (err) {
          if (err) throw err;
        });

        console.info('Success');
        break;
      } else {
        console.error('Fail to load [' + url + '] w/ status code: ' + status);
      }
    } catch (error) {
      console.error('Exception: ' + error)
    }

    console.info('Retrying ' + ++retries);
    await sleep(3000)
  }

  await browser.close();
};

const myArgs = process.argv.slice(2);
const url = myArgs[0]
const outputFile = myArgs[1]

getContent(url, outputFile);

Nov 27, 2019

Supercharged End 2 End Testing with CodeceptJS

IMO best End 2 End testing tool till now: CodeceptJS

Resource Links:

codeceptjs | CodeceptJS@github | CodeceptJS Doc | codeceptjs@npmjs

CodeceptJS Community | CodeceptJS@slack | codeceptjs@stackoverflow


Presentation/Tutorials:

Michael Bodnarchuk: EFFECTIVE END TO END TESTING WITH CODECEPTJS | video

Intro to BDD style E2E testing with CodeceptJS, Docker Compose and Semaphore CI

Visual Testing Powered by CodeceptJS & Resemble.js

End-To-End Testing With CodeceptJS (Registration test w/ codeceptjs-tempmail)

codeceptjs jenkins integration

Running End to End tests as Google Cloud Functions

Pros:
  • Support web and mobile;
  • Better locator
  • Parallel Execution
  • Better report (allure), logging (–steps --verbose --debug)
  • Interactive debugging (shell, but no VS Code step-by-step debug)
  • Active development

Daily cmds:
  • npm install codeceptjs --save; npx codeceptjs init; npx codeceptjs def .; npx codeceptjs [gt|gpo|go|gh]
  • npm install -g selenium-standalone; selenium-standalone install; selenium-standalone start or use codeceptjs-selenium
  • npx codeceptjs run --steps
  • npx codeceptjs run -o '{"tests":"./account_test/example_test.js"}' # run test in non-config path
  • allure serve output
  • For signup: codeceptjs-maildev-helper

Jun 18, 2019

JSON Tools - jq

Comparing with Python json.tool, seems jq is much light weight and powerful :)

Sample time diff:

With jq:
real 0m1.666s
user 0m0.262s
sys 0m0.290s 


With Python json.tool:
real 0m2.217s
user 0m0.492s
sys 0m0.539s



Useful links:

HTML parsing with Python


Scraping Data with Python and XPath:

Sample code from reference link which tell the whole story :)

import requests
from lxml import html

pageContent=requests.get('https://en.wikipedia.org/wiki/List_of_Olympic_medalists_in_judo')
tree = html.fromstring(pageContent.content)

goldWinners=tree.xpath('//*[@id="mw-content-text"]/table/tr/td[2]/a[1]/text()')
silverWinners=tree.xpath('//*[@id="mw-content-text"]/table/tr/td[3]/a[1]/text()')
#bronzeWinner we need rows where there's no rowspan - note XPath
bronzeWinners=tree.xpath('//*[@id="mw-content-text"]/table/tr/td[not(@rowspan=2)]/a[1]/text()')
medalWinners=goldWinners+silverWinners+bronzeWinners

medalTotals={}
for name in medalWinners:
    if medalTotals.has_key(name):
        medalTotals[name]=medalTotals[name]+1
    else:
        medalTotals[name]=1

for result in sorted(
        medalTotals.items(), key=lambda x:x[1],reverse=True):
        print '%s:%s' % result


BeautifulSoup is another option but different style from xpath.

Jun 13, 2019

HTML page parsing with xmllint xpath in BASH


Per HTML_parsers, there is no better HTML page parsing options for BASH. Inspired by Retrieve web using xpath, here comes the summary of using xmllint xpath:


xpath='' # sample: '//div[@class = "tides"]'

get_element_by_xpath():
    echo $HTML_PAGE | xmllint --html --xpath $xpath - 2>/dev/null

get_element_text_by_xpath():
    xpath+='/text()'
    echo $HTML_PAGE | xmllint --html --xpath $xpath - 2>/dev/null

get_elements_count_by_xpath():
    xpath="count($xpath)"
    echo $HTML_PAGE | xmllint --html --xpath $xpath - 2>/dev/null

May 10, 2019

Setup Bash Debugger in VS Code

Recent projects need some bash scripting, besides bashdb in terminal, GUI bash debugging make life much easier:

  1. Follow all steps in Upgrading Bash on macOS to update bash (need bash > 4.0)
  2. Install bashdb: brew install bashdb
  3. In VS Code:
    1. Install extension Bash Debug
    2. Configure bash debugger by https://marketplace.visualstudio.com/items?itemName=rogalmic.bash-debug
    3. Additional configure: add "terminalKind": "debugConsole" to launch.json to each configuration

Jun 16, 2018

API Automation Test

As per Top 10 API Testing Tools, API Test becomes a buzz word now because many companies nowadays require strong API performance and shifts towards APIs architecture, hence this summary post of API test.

Use Katalon

As I said in earlier post, I'm a fan of Katalon Studio which combines UI and API test in one Eclipse based user friendly IDE with valuable Recorder(record/play) feature! Only missing part is no direct support of performance test.

As shown in Create your first API test with Katalon Studio (manual style without scripting) and Katalon Web Service Test (video with a little bit scripting), Katalon supports API test in powerful user friendly way as other popular API test tools e.g. Postman, Restlet Client; By Parameterize a Web Service object and scripting, we could have all kind of APIs calls combinations.

The important point here is Katalon uses Groovy as scripting language, besides enjoy the beauty of Groovy, we have full control of the scripts flow! We could introduce any other external Java libraries into Katalon Studio to leverage all powerful features on Data-driven, assertion etc. integrating with UI/API testing. Even make up some performance test indirectly with coding around 3rd party libraries e.g. REST Assured.

Use long live JMeter

And still love JMeter if load test API after feature test is a must. JMeter is born for load test!
Pure Coding style using REST Assured

With REST Assured along come out home brew BDD style API test! Recommend tutorial.


Jun 15, 2018

Geb / Spock Gatling vs JMeter

is a browser automation solution. GEB = Selenium WebDriver + Java + Groovy + Jquery
It brings together the power of WebDriver, the elegance of jQuery content selection, the robustness of Page Object modelling and the expressiveness of the Groovy language.
It can be used for scripting, scraping and general automation — or equally as a functional/web/acceptance testing solution via integration with testing frameworks such as Spock, JUnit & TestNG.
Spock (same idea as Cucumber): 
Spock is a testing and specification framework for Java and Groovy applications. 
Spock lets you write specifications that describe expected features (properties, aspects) exhibited by a system of interest.

Gatling is a highly capable load testing tool. It is designed for ease of use, maintainability and high performance.
Out of the box, Gatling comes with excellent support of the HTTP protocol that makes it a tool of choice for load testing any HTTP server. As the core engine is actually protocol agnostic, it is perfectly possible to implement support for other protocols.
Gatling simulation scripts are written in Scala.

JMETER VS GATLING TOOL: https://octoperf.com/blog/2015/06/08/jmeter-vs-gatling/

Jun 3, 2018

Selenium WebDriver Automation Best Practices (Refer to testautomationguru)

Notes while learning from testautomationguru.com (THANKS!) which need strong development skills ;) With help of Katalon, seems most best practices could be implemented :) Keep the summary to remind best practices will always help!

1. Page Objects Model, + Arquillian Framework
  1. Page Objects: Page objects is a well known design pattern, widely accepted by the automation engineers, to create separate class file for each page of the application to group all the elements as properties and their behaviors / business functionalities as methods of the class. But it might not be a great idea always, especially when the page has more / different sets of elements / complex element like a grid / calendar widget / a HTML table etc. ex http://www.testautomationguru.com/keyword-driven-framework-for-localization-testing-using-selenium-webdriver/ (Table/keyword driven + page objects model)
  2. Selenium WebDriver – Blackbox Automated Testing using Arquillian Framework 
  3. Selenium WebDriver – Advanced Page Object Pattern with Page Fragments using Arquillian Graphene (Single Responsibility Principle)


3. Design patterns in Test Automation: http://www.testautomationguru.com/category/design-pattern/

"Note: Your aim should not be to implement a certain pattern in your framework. Instead, identify a problem in the framework and then recognize the pattern which could be used to solve the problem. Do not use any design pattern where it is not really required!!"

Refer to https://sourcemaking.com/design_patterns or http://www.oodesign.com/ for design patterns.

4. WebDriver in Fluent Style (java 8 Stream)

Selenium WebDriver – How To Design Page Objects In Fluent Style

5. Test Suite Management:
(By creating a custom annotation and using TestNG’s listener, We are able to skip methods without any issues and maintains the order the test execution.)

Katalon Introduction

Katalon

Recently find free (not open source) automation tool Katalon and love it, personally believe it will be more popular in near future, recommend everyone interested in automation no matter beginner or expert to take a look!  (No pay from Katalon for voluntary :D )

See what Wikipedia says about Katalon:
  • "The software is built on top of open-source automation frameworks Selenium, Appium with a specialized IDE interface (implemented on Eclipse) for web, mobile and API testing." 
  • "The main scripting language is Groovy, Java, and JavaScript and can be executed against all modern browsers, iOS, and Android applications supported by Selenium and Appium." 
  • "Katalon Studio follows the Page Object Model pattern." 
  • "The remote execution can be triggered by CI systems via Docker container or command line interface (CLI)."
Cool, right?! One more very important point missed on Wikipedia is the record and play feature. It's normally sale point of commercial automation tool (HP UFT/QTP, IBM RFT, TestComplete etc.). As a starting point or code snippet, it is a great time saving feature.

Object recognition support multiple methods to get job done which make scripts more tolerate to AUT changes, no as good as IBM RFT's but good enough.

For Selenium 1.0 IDE lover, Katalon Automation Recorder Chrome extension is the latest replacement.

Well organised Official Katalon site has all necessary information (docs, forum etc.)

There is a free Udemy course Automate everything with Katalon Studio.


Aug 31, 2010

IBM RFT: how to invoke object methods

Looks like currently IBM RFT only support Java domain objects methods invoke(?)

Three steps to invoke the object methods:

1. get all methods signature:

printTOMethods(TestObject TO) {
int i = 0;
System.out.println("Object Class [" + TO.getObjectClassName() + "]'s methods: \n");
for (MethodInfo mi : TO.getMethods()) {
System.out.println("Method-" + (i++) + ": [" + mi.getName() + ":" + mi.getSignature() + "]");
}
}

2. Study api documents to select the methods you need to use according to your target;
3. invoke object methods strictly obey the signature:

for example, for some 'new' objects RFT could only blindly click/select by screen point, you need to find the screen point for RFT:

boolean selectTableItem(ScrollTestObject table, String itemName) {
boolean selected = false;

TestObject[] itemsTo = (TestObject[])table.invoke("getItems");

for (int i=0; i
if (itemsTo[i].getProperty("text").toString().equalsIgnoreCase(itemName)) {
java.awt.Rectangle rec = (java.awt.Rectangle) itemsTo[i].invoke("getBounds", "(I)", new Object[] {new Integer(0)});
table.click(atPoint(rec.x + rec.width/2, rec.y + rec.height/2)); //click at the item center to select it

selected = true;
break;
}
}

return selected;
}

IBM RFT: Enable Java Domain for Java AUT

Normally IBM RFT just regards all objects in Win domain without respect that the AUT is a Java application.
It's fine normally, but for some special objects (e.g. grid) against which you'd like call the special methods for your test purpose, you could enable RFT to treat objects in Java domain:
  • In RFT, 'Configure->Enable Environments for Testing...';
  • In tab 'Eclipse Platforms', 'Add...' browse to where your Java application home_dir (with private jre);
  • 'Enable' it, then 'Apply', 'Finish' to close 'Enable Environments' window.

Aug 21, 2007

JMeter HTTPClient HTTP sample might be the reason of jmeter crash

As statement in some document that HTTPClient HTTP sample is more stable than simple HTTP sample, but it might also be the reason why jmeter crash since HTTPClient HTTP sample log too many messages in jmeter.log like below,

2007/08/20 16:05:35 INFO - org.apache.commons.httpclient.HttpMethodDirector: Redirect requested but followRedirects is disabled

In this case have to change back to simple HTTP sample:(

Jul 26, 2007

MS-DOS Batch Script Tips

Never suppose to write windows bat file. But when recently try it, even it really ugly comparing with unix shell scripts, still something interesting to learn and enjoy:)

rem setlocal not to impact environment variables
setlocal

rem get current disk driver and directory in case needed resources in specific location
set workDriver=%~d0
set workPath=%~p0
%workDriver%
cd %workPath%

rem call some command/executed program here
rem then check ERRORLEVEL for error handling
if ERRORLEVEL 1 (set errorCode=1
rem change color for warning and fun :)
color 4e
echo Error encounter!
pause
color 0f
goto error)

Useful link:
Batch File Command Reference for Windows 2000
MS-DOS/MSDOS Batch Files: Batch File Tutorial and Reference

Jul 12, 2007

Jmeter: Summary Report vs Aggregate Report

When using Aggregate Report listener in Jmeter script, the memory usage will increase linearly with the number of total samples grow. Which might be the biggest reason JMeter got out of memory for long period run. Reason is,

Warning in Aggregate Report help: "Calculation of the Median and 90% Line values requires a lot of memory as details of every Sample have to be saved. See the Summary Report for a similar Listener that does not need so much memory."

So use Aggregate Report only when you care Median and 90% Line values. But what Median, do you really care it, good explanation is here.

Jul 11, 2007

JMeter: BeanShell Example

For example, I need to handle number's get from web page which is return by HTTP Request Sampler. It's hard to get the number string directly from ResponseData sometime, just use a "Regular Expression Extractor" and store it to a temp variable, say _tmpAmount, then,

Script:

String amountString = vars.get("_tmpAmount");
int amount = Integer.valueOf(amountString).intValue();

int minAmount = 10;

if (amount > minAmount) {
vars.put("_finalAmount", Integer.toString(minAmount));
} else {
Failure = true;
ErrorMessage = "Must has at least " + minAmount + " in original account!";
SampleResult.setDataType(SampleResult.TEXT);
SampleResult.setResponseMessage(ErrorMessage);
SampleResult.setResponseData(ErrorMessage.getBytes());
SampleResult.setStopThread(true);
}

Jul 10, 2007

JMeter: Dynamic SOAP XML data of WebService(SOAP) Request

SOAP XML data of WebService(SOAP) Request could be set by,

a). "Soap/XML-RPC Data" text field directly or
b). reading from file or
c). randomly picking up from directory when data files stored.

When want to send dynamic soap xml data, say different user name, method a) doesn't work since it's hard coded; method c) works here as long as we generate the data files in advance.

How about method b)? It looks more neat, at least for me:) But how?

The way I could think about is using a Java Request before each WebService(SOAP) Request. In the Java Request, just use simple BufferedWriter writer = new BufferedWriter(new FileWriter("soapDataFile")) to generate the soap xml file which includes the dynamic user name variable read from user file. Since the xml is not complex, just regard it as text file, no bother to use the more professional heavy XML processing method like How to Read and Write RSS Feeds (Linked here just in case)

JMeter: BeanShell Usage

With JMeter, sometimes we need run to later samplers based on response from previous samplers to provide scripts' flexibilities.

Normally "Regular Expression Extractor" could get expected value from sampler response;

Otherwise we might need to use __BeanShell(), __javaScript() (examples) with the help of JMeter's "Options | Function Help Dialog";

For more complex cases, we might have to use "BeanShell Assertion"; How to debug it? Refer to BeanShell Manual and try it in BeanShell Desktop window before copy it to your "BeanShell Assertion". Where to start BeanShell Desktop? Download it from http://www.beanshell.org/download.html and save it to your jmeter_home/lib, just double-click bsh*.jar and play. Enjoy it:)

JMeter: HTTP Proxy Server doesn't support HTTPSampler2

In current JMeter version 2.2, in jmeter.properties's "JMeter Proxy recorder configuration" section, "Change the default HTTP Sampler" by removing "#" from line jmeter.httpsampler=HTTPSampler2, the HTTP Proxy Server supposed to recording the HTTP sampler by using HTTPSampler2, i.e. HTTPClient HttpSampler.

But unfortunately, we will got "ERROR - jmeter.protocol.http.proxy.Proxy: java.lang.NullPointerException" in jmeter.log and gateway timeout in browser. By checking http://article.gmane.org/gmane.comp.jakarta.jmeter.user/14834/match=jmeter+protocol+http+proxy+java+lang+nullpointerexception+httpsampler2 we could know, it's still not supported:(