Java, NoSQL, SQL, REST API and other scary words, QA (eng)

Cucumber – bridge or another one abyss between BA and QA

Cucumber Introduction:

Cucumber is a tool based on Behavior Driven Development (BDD) framework which is used to write acceptance tests for web application. It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.

Cucumber feature files can serve as a good document for all. There are many other tools like JBehave which also support BDD framework. Initially Cucumber was implemented in Ruby and then extended to Java framework. Both the tools support native JUnit.

Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code. We will discuss more about the BDD and style of writing BDD tests.

Cucumber could be used along with Selenium and Java and this is more than enough to make me happy.

Cucumber Basics:

In order to understand cucumber we need to know all the features of cucumber and its usage.

#1) Feature Files:

Feature files are essential part of cucumber which is used to write test automation steps or acceptance tests. This can be used as live document. The steps are the application specification. All the feature files ends with .feature extension.

Sample feature file:

Feature: Login Functionality Feature
In order to ensure Login Functionality works,
I want to run the cucumber test to verify it is working
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER” and Password “PASSWORD”
Then login should be successful
Scenario: Login Functionality
Given user navigates to SOFTWARETETINGHELP.COM
When user logs in using Username as “USER1” and Password “PASSWORD1”
Then error message should be thrown

Continue reading

Standard
Requirement management (rus)

Бесплатный онлайн-практикум для аналитиков

31 июля я и Александр Байкин будем вести новый онлайн-практикум для аналитиков

🔹Описание практикума
Этап сбора и анализа требований — один из самых ответственных в жизненном цикле разработки проекта. Если на данном этапе требование не будет выявлено или будет заложена ошибка, то, вероятнее всего, команда разработчиков узнает о ней только под конец проекта, и данную функциональную возможность потребуется заново специфицировать, разрабатывать, тестировать, а также повторно обучать заказчика. То есть ошибки, заложенные на этом этапе, будут самыми дорогостоящими.

🔹Цель практикума
Этот практикум разработан для Бизнес- и Системных аналитиков.
За время практикума, в котором участники проведут анализ бизнес-ценностей продуктов на рынке и проведут описание требований, будет создана доменная модель, и в завершении – будут поставлены задачи на разработку.

Это бесплатный практикум, основная ценность которого – получить практический опыт под руководством опытных наставников. Мы не предусматриваем длительных теоретических лекций, однако всегда подскажем – каким материалом воспользоваться для самостоятельного изучения. Также мы ожидаем, что все участники будут максимально общаться между собой, обмениваясь опытом.

🔹Аудитория
Любой специалист, который так или иначе сталкивается с проблемой сбора, анализа, описания и согласования требований.
Уровень аудитории: начинающий и средний.

🔹Длительность практикума 1,5 мес. План проекта.

🔹Кто мы
Александр Байкин и я имеем:
▪Более 25 лет опыта работы с требованиями.
▪Около 10 круглых столов под патронажем Luxoft и других организаций.
▪Курс Разработка и управление требованиями к ПО (https://www.webursitet.ru/product/kratkiy-kurs-sistem..) под эгидой Вебурситет и др.
▪Множество выступлений на конференциях (ЛАФ, Analyst Days, SECR и пр.) и семинарах.
▪Десятки статей в различных интернет-изданиях.
А также Александр является со-организатором Летнего Аналитического Фестиваля и Сообщества Аналитиков uml2.ru

🔹Записаться на практикум
Приготовьтесь к ОЧЕНЬ интенсивной работе и подайте заявку на практикум: Анкета регистрации

Standard
Java, NoSQL, SQL, REST API and other scary words

Best Practice to display image on a page

Let’s start with something simple – there are three universally supported image formats: GIF, PNG, and JPEG. In addition to these formats, some browsers also support newer formats such as WebP and JPEG XR, which offer better overall compression and more features. So, which format should you use?

1

At first – we should do a good work with images itself (this part is so boring, so, I’ll just provide a short list of recommendations):

  • Sizing. Developers / designers – make sure the images you deliver perfectly fit their required website dimensions. Even if the same image should be made into different sized thumbnails to fit different pages, it’s well worth creating all these different thumbnails rather than deliver a large image and rely on the browser to resize it.
  • Quality. don’t be afraid to experiment with lower JPEG quality levels. For certain websites we found that using a 50% JPEG quality yielded a very reasonable result.
  • Correct Format.Once again, PNG should be used for computer generated images (charts, logos, etc.), JPEG when you are showing a captured photograph.Notice that despite the common belief, PNG will outperform GIF in almost every other aspect.
  • Use compression tools
  • Useless data. Make sure you strip the meta-data off your images and user uploaded photos
  • Using images when CSS3 can be used. This one point is more interesting, but still, we are far away from algorithms. Just make sure you use CSS3 whenever possible. If your graphics designer is responsible for the markup, make sure you ask for CSS3 based elements where it makes sense. This thing should go as a non-functional requirement.
  • Incorrect image cache settings. we highly recommend using aggressive caching for all your website images by setting your images HTTP ‘Expires’ header to as far in the future as possible.
  • Using a single image size across all delivery mediums. The solution is pretty simple – identify your visitors mobile devices and resolution using their user agent and optionally additional client-side Javascript code. With the correct resolution in hand, retrieve the best fitting image from your servers.

Delivering static icons one by one

Other than photos and thumbnails, your website most likely includes many icons (arrows, stars, signs, marks) and auxiliary images. Google’s search results page is comprised of over 80 (!) tiny icons.

A simple solution for this problem is to utilize a CSS Sprite, a single image that contains all your smaller icons. Your web page is modified to download this single image from your server and the page’s HTML uses alternative CSS class names to point to the smaller images within the larger one.

Now, instead of 80 images, Google’s visitors download just a single image. Their browser will quickly download and cache this single image from Google’s servers and all images will be immediately visible.

To be honest, would also highly recommend Font Awesome to be implemented at your page.

Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Rest Chat – Avatars, News Feed and State Machine

So, as a next step I decided to implement Avatars, News Feed and State Machine.

Avatars

That was pretty simple to add avatars – add module which will handle image upload/cropping for future upload to the DB Avatar field. I found couple modules to add, but they are not 100% working:

  1. https://github.com/andyshora/angular-image-crop Zoom is not working for chrome 57.0 and angularjs 1.4.8
  2. https://github.com/allenRoyston/ngCroppie is not working at all (I made a bug – https://github.com/allenRoyston/ngCroppie/issues/32).
  3. etc

So, finally I found ngImgCrop module for this purpose.

State Machine

I used classic state machine to handle friendship statuses (and errors), so, I draw a pretty simple scheme with transitions and after that – excel file with description of every transition (including errors handling with proper messages). You will never see this error messages unless you would like to modify existing RESR URLs to try to approve friendship of some unknown user and etc.

Cause this is a pretty simple and well known area – here is some theoretical description and implementation of the state machine:

code snapshot:

case "Restore Subscription":
 switch (relationFriend){
 case 0: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 1: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 10: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 11: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 12: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 20: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 21: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 22: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 23: errorExists = 1;errorText = "There is no ignored friend. "; break;
 case 30: newRelationFriend=21; break;
 } break;
 case "Unsubscribe":

News Feed

In fact, news feed is a somewhat like a messaging, but with the different security and CQL statement of course. Therefore, new requirements for the New Feed are:

  1. Add News Feed item
  2. Edit News Feed item
  3. Delete News Feed item
  4. Add subscription
  5. Delete subscription
  6. Hide News Feed item from everybody
  7. Show News Feed item for friends only
  8. Show News Feed item for everybody
  9. Select favorite authors

I don’t want to make a full description for each requirement and don’t want to describe User Stories because I’m a Facebook user and requirements on this level are pretty obvious and straight forward. I skipped some of these requirements during implementation and will implement them during some of the next iterations.

Let me describe my current database structure (I used draw.io for that):

Let me introduce DB changes:

1)  Introduce new object to store News Feed items

2) Add fields to store avatars

So, as a result I got this demo video and a bunch of items for the next version at my backlog.

Standard
Java, NoSQL, SQL, REST API and other scary words

Cassandra Datastax and Java – best way to set up connection

I’ll research the best way to make a connection from my Java to Cassandra here. There are a lot of examples how to do that, but the main thing, but I’m developing some kind of chat application on my localhost (will do single insert/update statements, etc.) when all this Spark examples are perfect for analytical workflows.

The first one example is Spark 1.6:

public static JavaSparkContext getCassandraConnector(){
         SparkConf conf = new SparkConf();
         conf.setAppName("Chat");
         conf.set("spark.driver.allowMultipleContexts", "true");
         conf.set("spark.cassandra.connection.host", "127.0.0.1");
         conf.set("spark.rpc.netty.dispatcher.numThreads","2");
         conf.setMaster("local[2]");

         JavaSparkContext sc = new JavaSparkContext(conf);
         return sc;
    }

So, I also got an example for Spark 2.x where the builder will automatically reuse an existing SparkContext if one exists and create a SparkContext if it does not exist. Configuration options set in the builder are automatically propagated over to Spark and Hadoop during I/O. Continue reading

Standard
QA (eng)

Test Suite Report Builder Comparison

Here is a short comparison of for most popular ways to build test report for TestNG + Java framework (with comparison table in the end of the post).

Log4J

This is a pretty simple logger which throws test suite execution to the Windows Console, Eclipse Console and text file.

There is no screenshot capturing or easy navigation between multiple suites, so, this is just a huge text file.

1 Continue reading

Standard
QA (eng)

Test Framework (Java, TestNG, ANT, etc)

Introduction to Automation testing:

Testing is an essential part of a software development process. While testing intermediate versions of products/projects being developed, testing team needs to execute a number of test cases. In addition, prior to release every new version, it is mandatory that the version passed through a set of “regression” and “smoke” tests. Most of all such tests are standard for every new version of product/project, and therefore can be automated in order to save human resources and time for executing them.

Benefits of using automated testing are the following:

  • Reduction of tests’ time execution and human resources required
  • Complete control over the tests’ results (“actual results” vs “expected results”)
  • Possibility to quickly change test’s preconditions and input data, and re-run the tests dynamically with multiple sets of data

Automation workflow for the application can be presented as follows:

  • First of all it is required to identify tasks that an application has to accomplish.
  • Second, a set of necessary input data has to be created.
  • Third, expected results have to be defined in order one can judge that an application (a requested feature) works correspondingly.
  • Fourth, Executes a test.
  • Finally, Compares expected results with actual results, and decides whether the test has been passed successfully.

Goal:

The goal of this framework is to create a flexible and extendable automated testing framework, which should expand test coverage for as many solutions as possible. Framework must have input and output channels and library of methods to work with UI.

Environment Specifications:

  • Selenium Webdriver. Selenium is a suite of tools for cross-platform automated testing of web applications. It runs on many browsers and operating systems and can be controlled by many programming languages and testing frameworks. Selenium WebDriver is a functional automation tool to automate the applications. It makes direct calls to the browser using each native support for automation.
  • Eclipse IDE. Eclipse is an integrated development environment (IDE) used in computer programming, and is the most widely used Java IDE. It contains a base workspace and an extensible plug-in system for customizing the environment. Eclipse is written mostly in Java and its primary use is for developing Java applications.
  • Java.
  • TestNG. Is a testing framework inspired from JUnit and NUnit. It has extended new functionalities, which made it more powerful and easier than the other testing frameworks. It supports ReportNG (simple HTML reporting plug-in) and XLST (Graphical / Pictorial reports) plug-ins to customize or extend the default TestNG reporting style. TestNG also provides ability to implement ‘IReporter’ an interface which can be implemented to generate a Customized TestNG report by users. It has ‘generateReport()’ method which will be invoked after all the suite has completed its execution and gives the report into the specified output directory.
  • Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications.
  • AutoIT Tool used to handle Windows popups for Document Uploads and Downloads.
  • Apache POI to perform operations with excel like read, write and update the excel sheet
  • Webdriver is a driver that contains programming interface for controlling all kinds of possible actions in browser.
  • Selenium TakesScreenshot to take screenshot in case of error.
  • Log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License.
  • JDBC. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is part of the Java Standard Edition platform, from Oracle Corporation.

Continue reading

Standard
QA (eng)

Test Suites for Simple Chat Application (REST API)

Introduction

This is a framework with test suites which allows me to test my Simple Chat Application UI in 5 minutes.

test app

I could provide bitbucket project access upon request and this is a link to original chat application.

Short Demo

Architecure

  • TestNG and Java
  • Webdriver is a main test library
  • JDBC to work with DB (clean up test data)
  • ANT to display test results
  • Test Suites and data stores as xls files and their status updates with every run
  • Easy to use with Jenkins

Framework example to begin with

Step by step instruction how to create framework

Standard
Java, NoSQL, SQL, REST API and other scary words

Simple Chat Application (REST API)

Introduction

This is a simple restfull chat application to send messages between friends. Key features:

  • Register to the System
  • Login
  • Send/Approve Friendship Request
  • View friends list
  • Ignore User
  • Send Message
  • Delete account Minor features:
  • Auto update messages and friends lists
  • Security by Token

Link to the project upon request.

Short Demo

Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Load Balancing for Dummies

The long story short – sometimes your application on a server got too many requests and you make a decision to add a brand new server. The question is – how to balance the load between these 2 servers?

Cause we are talking about about theoretical and simple things only – there are 3 basic methods:

  1. Round Robin
  2. Least Connect
  3. Weighted Least Connections

Round Robin is one of the simplest methods for distributing client requests across a group of servers. Going down the list of servers in the group, the round-robin load balancer forwards a client request to each server in turn. When it reaches the end of the list, the load balancer loops back and goes down the list again (sends the next request to the first listed server, the one after that to the second server, and so on). Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Most popular and simple Search and Sort algorithms

Binary Search

Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].

  1. Compare x with the middle element.
  2. If x matches with middle element, we return the mid index.
  3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
  4. Else (x is smaller) recur for the left half.

Search an element in a sorted and rotated array

Input  : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}; key = 3

Output : Found at index 8

1) Find middle point mid = (first_element + length)/2

2) If key is present at middle point, return mid. if (arr[mid] == key) return mid;

3) Else If arr[l..mid] is sorted

  1.    a) If key to be searched lies in range from arr[l]

      to arr[mid], recur for arr[l..mid].

  1.    b) Else recur for arr[mid+1..r]

4) Else (arr[mid+1..r] must be sorted)

  1.    a) If key to be searched lies in range from arr[mid+1]

      to arr[r], recur for arr[mid+1..r].

  1.    b) Else recur for arr[l..mid]

Continue reading

Standard
Java, NoSQL, SQL, REST API and other scary words

Array Algorithms

Reverse an array or string

Input: 123

Output: 321

1) Initialize start and end indexes (start = 0, end = n-1).

2) In a loop, swap arr[start] with arr[end] and change start and end as follows (start = start +1; end = end – 1)

Given an array A[] and a number x, check for pair in A[] with sum as x

1) Sort the array in non-decreasing order. sort(A, 0, arr_size-1);

2) Initialize two index variables to find the candidate elements in the sorted array.

   (a) Initialize first to the leftmost index: l = 0

  (b) Initialize second  the rightmost index:  r = ar_size-1

3) Loop while l < r.

   (a) If (A[l] + A[r] == sum)  then return 1

   (b) Else if( A[l] + A[r] <  sum )  then l++

   (c) Else r–

4) No candidates in whole array – return 0

/* The main function that implements QuickSort() arr[] –> Array to be sorted, low  –> Starting index, high  –> Ending index */

static void sort(int arr[], int low, int high)

{

    if (low < high)

    {

        /* pi is partitioning index, arr[pi] is now at right place */

        int pi = partition(arr, low, high);

        // Recursively sort elements before partition and after partition

        sort(arr, low, pi-1);  sort(arr, pi+1, high);

    }

} Continue reading

Standard