Drupal Commerce: Splitting a package into multiple shipments using Packer & PackerManager

Drupal 8 commerce shipping contributed module introduced an extendable and prioritized concept of Packer and PackerManager. Packer allows sites to automatically split an order into multiple shipments based on stock location, weight, dimensions, or some other criteria.

Let’s see what Packer and PackerManager do.

Packer and PackerManager

  1. Packer: Creates one or more shipments for a given order. We can create an end number of Commerce Packer class, which implements `Drupal\commerce_shipping\Packer\PackerInterface`. PackerInterface provides abstract methods:
    1. applies: Determines whether the packer applies to the given order.
    2. pack: Packs the given order.
  1. PackerManager: Runs the added packers one by one until one of them returns a result.

How PackerManager works

Based on each Packer priority, PackerManager will check whether the packer applies for an order or not. If packer applies for the concerned order than it will execute the pack method. This iteration will go on until any one of the Packer returns a proposed shipment.

Commerce shipping contributed module implement DefaultPacker, which creates a single shipment per order. If we have implemented one or more Packer classes, then we have to prioritize the packers.

Implementing multiple shipments

  1. Create Packer class.

  2. Implement applies method, here this custom packer doesn’t apply to China location.

  3. Implement pack method.

  4. Tag Packer in module services.yml

Finally, Packer class will be as below:

That’s it! This is how we split the package into multiple shipments in Drupal 8 Commerce. The method that I espouse above is all about creating a good experience for customers. We recommend you to try out Packer and PackerManager concept to find out what works well for your ongoing projects.

Configuring Memcache with Drupal 8 to reduce database load

Developers often come across a situation where they are required to reduce database load by caching DB objects in RAM. Here Memcache improves Drupal application performance by moving standard caches out of the database and by caching the results of other expensive database operations. 

Note that Drupal doesn’t support Memcache by default, and for this, we need to install it on the server. Let’s see how to install Memcache on the server and configure it with Drupal 8 to reduce the load on the database with every page load.

Let’s see how to install Memcache on server

Open the terminal on your local machine and run the following codes:

Step 1: sudo apt-get update

Step 2: sudo apt install memcached

Step 3: sudo apt install php-memcached

Step 4: Make sure Memcache daemon is working fine by running the following command: 

“ps aux | grep memcached”

Step 5: Also, check whether the Memcached extension is properly configured in PHP7 by creating info.php page.

nano /var/www/html/memcache/info.php

And enter the below code 

 

Step 6: Now restart both Memcached and php7-fpm services 

service memcached restart
service php7.0-fpm restart

Step 7: Go to any web browser and access info.php as 

“localhost/memcache/info.php”, and search for “Memcache” you will see the screen similar to the one mentioned below.

Memcache server

After installation of Memcache in your server, download Memcache module and Memcache Storage module.

 

Now go to “http://yourdomain.com/admin/modules” and enable the two modules.

Memcache Enabled

Configuring Memcache with Drupal 8:

Open your site settings.php and paste the below code. Here we are using Memcache storage for Drupal 8 as it provides an integration of D8 and Memcached PECL.

// Set’s default cache storage as Memcache and excludes database connection for cache
$settings['cache']['default'] = 'cache.backend.memcache_storage';
// Set’s Memcache key prefix for your site and useful in working sites with same memcache as backend.
$settings['memcache_storage']['key_prefix'] = '';
// Set’s Memcache storage server’s.
$settings['memcache_storage']['memcached_servers'] =  ['127.0.0.1:11211' => 'default'];

To debug Memcache include below code following above code in settings.php

// Enables to display total hits and misses
$settings['memcache_storage']['debug'] = TRUE;

Memcache debug

Note: Before uninstalling Memcache and Memcache storage, comment/delete Memcache settings code from your settings.php file.

That’s it! If you are planning to configure Memcache with Drupal, you need to look out for three things: which cache bins will be offloaded with Memcache; website traffic and volume of content; and the amount of RAM allocated to Memcache. 

Now you know how to configure Memcache with Drupal 8 to reduce database load. Go ahead and try it on your own website. In case you need any help in installing and configuring Memcache with Drupal 8, do leave a comment below and I will get back to you ASAP!

Related: Using SteemSQL to query Steem database

Below given is a presentation on "How to install Memcache on the server and configure it with Drupal 8."

References

dropsolid.com/en/blog/memcache-drupal-8 
https://www.drupal.org/node/2448995 
openconcept.ca/blog/mmallett/apc-varnish-memcache-and-caching-beyond-drupal-core

Resolving translation issue of Placeholder in Drupal 8

Hello Drupalers! Here is another #Tips&Trick to make your placeholder translatable. Recently, I have an opportunity to fix one of the issues in Drupal 8 instance where the website was not multilingual hence unable to handle internationalization. After fixing the issue, the contact form now supports more than 25 languages. Let me explain you, what exactly was the issue over here? And how did we overcome this issue?

Issue: Here, Drupal Contact Form Placeholder was not translatable from User Interface Translation.

As we all know anything passes through t() function is always translatable. The issue is generally found in Drupal 8, not sure whether it occurs in Drupal 7 or not. To check the same in Drupal 7, you need to use contributed locale module and check whether web form placeholder gets transformed or not when we do the translation. Remember, Placeholder does pass through t() function.

Notably, all text that passes through t() are visible in User Interface Translation. However, there is no such option to create the translation of a custom text. There many of us have difficulties in translating the text.

See the screenshot below for an example:

Core Drupal Translation UI

Workaround: To add Custom placeholder through your module in the form field.

Form Manage field placeholder setting

 

Don’t add it through field setting, leave it blank. We will add it through a custom module or custom Twig File. Here, Placeholder text should pass through t().

Adding Placeholder through custom module in the form

Scenario 1: To add custom placeholder to your form.

/**
 * Implements hook_form_form_id_alter().
 */

function custom_form_contact_message_feedback_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
          $form['field_name']['widget']['0']['value']['#placeholder'] = t('custom placeholder needs to be translate’);
}

Way to add through custom Twig file in your form

Scenario 2: To add custom string to your template file or twig.


 
{{ 'custom placeholder needs to be translate'|t }}

Once we have added our custom placeholder to custom module or twig, it should start displaying in User Interface Translation. And from there we can add translation for our choice of language. See the screenshot below for an example of ‘Filter Translatable Strings’.

Filtering Translation

Once it is visible on User Interface Translation, add text for your respective language and save the translation. Here I am adding text for the Hungarian language.

Custom Placeholder started displaying in Translation UI

 

Below is the sample for contact form after applying the solution.

Contact form Sample

The above step is one of the workarounds to translate custom text in Drupal 8 using custom code and Core User Interface Translation. Possibly, you can import .po file of respective languages by exploring & importing the same file with updated msgid & msgstr.  Let me know if you come up with a better solution for the above-mentioned issue.

Valuebound, we are fully on the Drupal 8 bandwagon - from an internal, client site development to consulting services. Our development team has been working with Drupal 8 as a group for over a year. Are you interested in learning more about how Drupal can help your business grow? Contact Us.

 

Build your own mobile app using Ionic and Drupal 8

Ever since the release of Drupal 8, the most popular keyword search in the framework is “Headless Drupal” also referred as Decoupled Drupal. Headless Drupal is something where you use Drupal to store data that can be accessed in multiple applications (via REST APIs). The front end frameworks like Ionic interacts with Drupal using HTTP requests.

Check out how to use this feature of Drupal and Ionic framework to build a hybrid mobile application.

What is Ionic?

In simple terms, Ionic is an open source framework that is built atop Apache Cordova to develop hybrid mobile apps. Hybrid apps are not developed specifically for a platform that means you can manage a single codebase for different platforms. Let’s build a simple movie listing page.

Prerequisites:

Installing Ionic:

  • To install Ionic you need to install  Apache Cordova, nodejs, npm in your system. Run the following codes.

sudo apt-get install nodejs
sudo apt-get install npm
sudo npm install -g cordova
sudo npm install -g ionic

Drupal Set up :

Enable the following modules for rest API

Modules required

  • Enable CORS (Cross Origin Resource Sharing) for accessing the data between applications. Change the CORS config as per the origins of services.yml file:
     
  • A content type of the movie :
    content type
  • A rest export view with a list of movies:


Rest View

  • Make the serializer format to be json.

    Integrating Drupal set up with Ionic

Step 1 - Create an Ionic menu-based app using the below command:

ionic start  sidemenu

You can choose tabs/blank instead of side menu for your app.

Step 2 - Run the app. Navigate to the app folder.

Ionic serve / ionic serve --lab (This allows you to view your app in both ios and Android platforms)

This opens the app in your desktop browser.

Step 3 - Create a page:

ionic generate page movie-list

Step 4 - Navigate to app folder. Edit the movie-list.ts from App Folder > src > pages > movie-list. This is where the view will be requested for data.

Step 5 - Now display the view data in the app.

The movies variable declared in movie-list.ts can be accessed in the movie-list.html. Below ion-header (similar to head in HTML), add ion-content (similar to body in HTML).

The sanitizer.bypassSecurityTrustHtml is used to save the html tags exposed from views.

Step 6 - To add the page to the menu, edit the app.component.ts file from App Folder > src > app.

Import your page at the top and add the page in pages variable.

Step 7 - Now check your app in the browser. You will be able to see the movie list page on the menu. You may see the output similar to the below screenshot. :

Result

You can apply the CSS for the ratings in app.scss file. The CSS applied here would be applied globally. If you want to apply styles to the specific page, you can create a .scss file in your page folder.

You may need to import some app components like HTTP, Headers for HTTP calls if facing any errors.

Login functionality can also be implemented as follows:

Login form in login.html would be

The form can be validated in login.ts.

The authenticated actions in Drupal like adding content can be done by passing the CSRF token stored in the local storage into headers.

You can also refer Ionic website to check out more details about deploying the app

In this way, you can use the Ionic framework to build the hybrid mobile apps and use the decoupling feature of Drupal to store the data. Try Ionic and see how it enhances digital experience. If you have any suggestions or queries please comment down let me try to answer.

 Below given is a presentation on "Building mobile app using Ionic framework."

 

 

Migrating Address Book in Drupal 8 website using Process plugin

Migration is a term, which all the developers who have started working in Drupal 8 have gone through once at least in their development cycle. Migration can be done of many things like site migration (i.e migrate from Drupal 7 to Drupal 8), user migration, content migration. In simple terms, we can migrate all types of entity in Drupal 8.

How this migration works:

Migrate works by reading a row from a source plugin then running each property through a pipeline of Process plugins thus, resulting in a row to a destination plugin.

Why we write Process plugin?

Each Process plugin gets the current value and returns a value.

Here we are going to look how this Process plugin works. We are going to migrate Address fields using Process plugin in Drupal 8. Follow the below steps.

Step 1: Install the following modules

  • Migrate Tools
  • Migrate plus
  • Migrate Source CSV

Step 2: Create a custom module. ‘custom_addressbook_migration’

  • Create a .info file :

Step 3: Create assets folder inside the module and paste your CSV file inside it.

  • Prepare the CSV as shown : 

Address_csv

 

Step 4: Create Process plugin

  • Add a new plugin class, called AddressFieldMigration, in your module at src/Plugin/migrate/process/AddressFieldMigration.php.
  • The @MigrateProcessPlugin annotation tells migrate about the new Process plugin and the id key is used to select this plugin in a migration’s mappings. The class should extend Drupal\migrate\ProcessPluginBase and override the transform() method. This method will be passed to the incoming source value and is responsible for returning the modified destination value.
  • Here, in CSV, we are passing the country name, but address requires country code so we have made use of  CountryManager Class to get the country code from given country name.
  • We get the region names in form of code mostly for Foreign Countries, In the CSV, you can see it is given as  ‘CA’. So, to get the state name we have to make use of methods from SubdivisionRepository Class.

Step 5: Now, we have to create a Migrate Configuration file and import this configuration.

Here,

  • Address is created under profile entity so the destination plugin name is entity: profile.
  • Process plugin is written to map all the columns given in source CSV file to its respective fields in address entity. In Migration, always we have to mention the source, destination, and process.

Step 6: Import the above configuration file into Drupal site.

  • Goto admin > config > development > configuration
  • Click on Import Tab and Choose Single Item
  • Select the Configuration Type as Migration
  • Paste the above configuration file and click on Import.

Step 7: Drush Commands to implement

  • drush ms - you will see the status of all the migrations.
  • drush mi address_fields_migration.('address_fields_migration' is the id in the configuration file)

Step 8: Conclusion :

  Now, Go to admin > config > people > profiles and you will see the list of address that has been migrated. This is how address fields are migrated using process plugin in Drupal 8.

To know more about migration using Process plugin, Refer Drupal 8 Process Plugin

Since I have mentioned only a few drush commands related to migration, you can check more about this Here

Please put your doubts, suggestions or queries related to above topic in the below comment box, and I will try to answer them. You may also like to check out our previous blog on "Drupal 8: Why & How to Migrate".

 

Enabling custom web font in Drupal website

This blog will walk you through one the contributed module in Drupal community that has been a heave of sigh for me whenever I was in trouble for web building activity. A couple of weeks back, I have been assigned a task where the requirement was to enable ‘Benton-sans Regular’ font throughout the site. Initially, I thought it would be an easy task and can be done easily. But I was wrong.

No issues! If you facing similar difficulties. Here, I am going to discuss how you can enable ‘Benton-sans Regular’ font seamlessly using Drupal font-your-face module.

Firebug Developer console

 

Earlier, I thought of writing a custom CSS for all the basic usable tags like

,,

,

,

,

,

,
,,,

by adding a font attribute ‘Font-family’. However, I was not cognizant of the font availability that it is equally important to render content with new fonts. At that point of time, the only values that were present on Firebug to debug was  -webkit-body, -webkit-pictograph, cursive, fantasy, inherit, initial, monospace, sans-serif, serif and Unset.

 

Solution: Here I am going to share the same solution that I applied to the above-mentioned issue. After doing little research I came across a font-your-face module that turned out to be a life savior for me. Note that there are many other lightweight modules available in community, such as  

  • , and

    Icon fonts (https://www.drupal.org/project/iconfonts)
    Google fonts (https://www.drupal.org/project/google_fonts)
    sweaver (https://www.drupal.org/project/sweaver)

    The reason behind choosing font-your-face module is that it offers admin interface to manage and apply new fonts. With this module, admin can also add module through CSS selector and enable font for the sub-theme.

    Prerequisites: Font file is required to enable Font. Here format should be EOT(embedded opentype) or TTF (truetype fonts) or WOFF (Web open font format), SVG (Scalable vector Graphics font format). Below is the list of the browser that supports Font format type.

    Font compatble browser list

     

    Let’s start by enabling the contributed module.

    Module enabling

     

    Here Providers display enabled font count, Advanced provides a checkbox (see below) and Preview holds sample text to be displayed while previewing enabled font.

    Checkbox

    Select the ‘Load fonts in all themes, including themes’ checkbox
     

    font-your-face configuration page

    Note: While adding a new font to the site, admin can provide basic information like font name, style of the font (Normal, Italic, Oblique), CSS font weight (Normal, bold, Bolder, lighter, 100, 200, 300, …..900).
     

    Import local font

     

    Browse local font

     

    By Font: This tab allows you to add CSS selector class. Select the checkbox and save the setting.

    Editing enabled font

    Once you save the setting, Font tab will start listing up Enabled Fonts.

    individual tag setting for font

    By CSS Selector: This tab lists HTML tag where admin can individually assign a font to each tag. Now click on save applied fonts.

    HTML tag selecting font setting page

     

    After assigning a new font to the desired tags, you can see the font reflection while loading the page.

    Note: Don’t forget to clear the cache.

    That's it! The above steps are walk-through for ‘@fontyourface’contributed module that supports multiple service provider like Typekit.com, google font, font.com, font Squirrel and Fontdeck. There are many other lightweight modules available in drupal.org that you can choose as per your requirement.

    We, at Valuebound, recommend trying out multiple font styles to find out what works well for your current project or requirements. Also, we invite you to comment below or ask any questions you may have.

      • Go for the normal installation as we do for all contributed module.
      • Click on Configure button, it will redirect you to 127.0.0.1/local/admin/config/user-interface/fontyourface
      • Now under General quick tab, you can see three different options: Providers, Advanced and Preview
      1. Load fonts in all themes, including admin themes.
      2. Keep detailed watchdog logs
      • Import Local Font quick tab having Font information fieldset with multiple font type upload option.
      • Now upload your choice of Font file like EOT/TTF/ WOFF/ SVG and click on confirm button.
      • Now under @font-your-face, enable fonts tab that has three sub-tabs, namely:
      1. By Font
      2. By CSS Selector
      3. In Themes

Getting started with Apache Cordova to build hybrid mobile apps

With the technological advancement, the demand for gadgets and their mobile apps are at its peak driving software industry to enhance digital experience. Interestingly, the apps designed for various operating systems are turning smartphones and tablets into miniature powerhouses of function and fun. Here I am going to share my first-hand experience of building a hybrid app using Apache Cordova.

So what is PhoneGap?

PhoneGap is an open source framework that allows us to build native mobile apps using various web-development languages such as HTML, CSS, and JScript; instead of relying on platform-specific APIs like those in iOS, Android or Windows. Developing mobile apps for each OS requires an optimum level of knowledge of different frameworks and languages, however, PhoneGap solves this issue by using standards-based web technologies.

How does it work?

The UI for PhoneGap applications is developed using the basic web-development languages and thus the browser takes 100% width and height of the device. Basically, it provides an API that enables to access native operating system functionality using JScript. You build your application logic using JavaScript, and the PhoneGap API handles communication with the native operating system.

PhoneGap

For demonstration, lets us build an app that will redirect us to a news publishing website. Run the codes to get the interface of a basic web page as shown in the image below.

When you will complete the installation, you will be redirected to the news page that contains the description of the news with a link to the main article. The following images are for reference.

Web page desktop version

 

Developing hybrid mobile application

Let’s gear up to turn the webpage into a hybrid mobile app. Here we will be pushing the code to the PhoneGap build cloud where the apps are developed on the specified preferences and requirements throughout all the mobile platforms.

To build a hybrid app through PhoneGap Build we require a config.xml file. We can find config.xml file in the root folder on the same level as that of the index.html.

Applications created with PhoneGap can be distributed to app stores, such as Apple App Store that can be installed on a user's device like any other native application.

Config.xml file:

This is the config.xml file which we are using in this example. Here you can find the whole set of code is enclosed in the widget tag.


Here,

 -- XML tags.

-- widget tag that has xmlns and xmlns:gap attribute which are for XML namespace

id = "com.valuebound.myapp"

-- The id attribute inside of the widget tag is used to uniquely identify the app on the PlayStore/iTunes and should be unique for every app and must be in the reverse domain notation.

versionCode = "10"

-- The versionCode attribute is used by the only android to identify different versions of the same app, so if you publish an app with versionCode=1 when you push an update to that app you will need to increment the number so for the next update you have to put versionCode=2 and so on.

version     = "1.0.0" >

-- The version attribute follows the  standard version system which is [major].[minor].[build]

PhoneGap TECHX

-- The name tag is the name of your app. This is not the name that will be used in the PlayStore/iTunes but it will be the name of the app on a device.



     An example for phonegap build docs.

--The description is pretty self-explanatory.



-- PhoneGap utilizes the tag to customise your application configuration. All tags in your config.xml are copied to the platform-specific configuration files, which implies that any preferences supported by the Cordova framework, or by any plugins.  [This is where we are specifying the preferences like for example the version of the Android or the screen resolution whether it should be portrait or landscape etc]



-- A plugin is a package of injected code that allows the Cordova web view within which the app renders to communicate with the native platform on which it runs. It provides access to device and platform functionality that is ordinarily unavailable to web-based apps. Have a look on other plugins.

PhoneGap web version

Notably, the above-mentioned UI is developed using PhoneGap Build and all the details (app name, app version etc.) that we provide in the config.xml file reflects here. This blog provides a reference for building Android mobile apps only. Here we are uploading the files to the cloud to build the app.

Once the config file is made we upload into the PhoneGap build cloud in a .tar file format. After completing the process, the interface will look similar to the web version of the smartphone.

Mobile Version

At the end, choosing the right framework for you will depend on your needs. Frameworks are made to make application development easier. It cuts off the time in making your site responsive in half. Try Apache Cordova to build your own app and see what it can do for you. If you have any suggestions or queries please comment down let me try to answer.

Below given is a presentation on Apache Cordova

 

References

Configure Apache Solr with Drupal for better content search

There have been times when clients are not very satisfied with the default Drupal search as it does not meet their requirement especially when you need specific search control beyond core e.g. facets and related content. In order to resolve this issue and make search fast for end customers, we can use Apache Solr - an open source enterprise search platform - and configure it with our Drupal site.

In one of our previous blog post, we have discussed “How To Create Custom SOLR Search With Autocomplete In Drupal 7”. Note, before creating custom Solr search, we need to set-up Solr in the server and configure with Drupal, and this is what I am going to talk about on this blog. Here, we will also learn to create the core in Solr. Unlike Ubuntu, you can also set-up Solr on Windows machine.

You may also like to check out our previous post on Installing & configuring Apache Solr-5.2.0 with Drupal 7 using Search API on Ubuntu 14.04.

Note: In the above-mentioned blog, Apache Solr - 5.2.0 is configured with Drupal 7 and in this blog, I am configuring Apache Solr - 6.6.1 with Drupal 8.

Prerequisite

Setting up the Java environment

As we all know, Solr is a Java application and to setup Solr we need Java runtime environment.  Also, we need to install Python software properties to install the latest Java 8. 

You can run the following commands to install Python software.

sudo apt-get install python-software-properties

After executing the command, add the webupd8team Java PPA repository in your system by running:

sudo add-apt-repository ppa:webupd8team/java

Then update the package lists to fetch the available packages from the new PPA:

sudo apt-get update

Now install the latest version of Oracle Java 8 with this command:

sudo apt-get install oracle-java8-installer

After installing Java, check the version by running the following command:

java -version

Installing Solr application

Step 1 Download the latest version of an available package from Apache web page using the wget command. For this setup, I am using Apache Solr 6.6.1 

Cd /tmp
Wget http://www-us.apache.org/dist/lucene/solr/6.6.1/solr-6.6.1.tgz

Step 2 Now run the below-mentioned command to extract the service installation file:

tar xzf solr-6.6.0.tgz solr-6.6.0/bin/install_solr_service.sh --strip-components=2

Step 3 Install Solr as a service using the script:

sudo ./install_solr_service.sh solr-6.6.0.tgz 

Step 4 Use the given below command to check the status of the service

service solr status

Step 5 After installing the Solr, create the core in the Solr.

Note: This is an important step so that we can index the contents to the Solr

By running the following command, core will be created in the solr server. 

Here, first_solr_core is the name of the core

sudo su - solr -c "/opt/solr/bin/solr create -c first_solr_core -n data_driven_schema_configs"

Now that Solr core has been created, you can check it in the solr dashboard.

Apache solr dashboard

Configuring with Drupal 8

After installing Solr in Ubuntu you need to configure it with Drupal 8. Let’s see how to do it step-by-step:

Step 6 Download the search api solr module and copy the files from Solr-conf directory respective to Solr version installed. 

Example: In this, we will copy all the files from search_api_solr/solr-conf/6.x and put that files under /var/solr/data/first_solr_core 

Step 7 Restart the Solr server by using the following command:

Sudo solr service restart

Okay, so now you know how to setup Apache Solr in Ubuntu and configure it to speed up your Drupal search. Just to let you know, for me it worked and I successfully configured Solr with Drupal site for one of our client. Go and try Solr on your website and see what it can do for you. Do share your experiences by commenting on this post.
 

Continuous integration using Jenkins and GitHub to automate deployment

Continuous Integration (CI) is rapidly becoming an integral part of software development process as it makes our monotonous and repetitive tasks a little less grindy. CI is a project development practice where developers integrate code into a shared repository frequently. Each Integration is then verified by an automated build that allows the team to detect problems in an early stage. 

This post will walk you through the continuous integration with Jenkins and GitHub. Here we will install Jenkins, create Jenkins task and then configure it with GitHub.

Let’s get our arms around why Jenkins is so popular and why this is not just a hot topic, but an important best practice for developers.

Related: Git and GitHub for Beginners

Why Jenkins is so popular for Continuous Integration?

Jenkins is an open-source tool that tests and compiles the code. If everything is fine then it deploys the code for production else you will get a notification that builds has failed and you need to fix the bug/error. Similarly, Selenium - an automation testing tool - minimizes the testing time and eliminates repetitive human tasks. 

Jenkins has an array of advantages, such as:

  • Easily configurable
  • Platform independent
  • Rich plugin support
  • Easy to create new Jenkins plugin if one is not available

Now you know why Jenkins is so popular, go ahead and install it. 

Step-by-step guide to Install Jenkins

Follow the below steps:

Step 1: First install Java, using the following command. 

$ sudo apt-get install openjdk-8-jre-headless -y

Step 2: Add the key and source list to apt for Jenkins.

$ wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key add -

Step 3: Now create source list for Jenkins, using the below commands

$ sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'

Step 4: Update the packages

$ sudo apt-get update

Step 5: Now install Jenkins.

$ sudo apt-get install jenkins

Step 6: After installing Jenkins. Go to: http://your_ip_address:8080 and run the following commands to get admin password.

$ sudo nano /var/lib/jenkins/secrets/initialAdminPassword

Step 7: Now copy the password and paste into browser.

Getting started with jenkins

When finished, you should see a screen similar to the below one.

Jenkins home page

Integrating GitHub with Jenkins

The integration of GitHub with Jenkins automates deployment, testing and improves products quality while saving a significant amount of time of developers. Follow the below steps to integrate GitHub with Jenkins:

Prerequisite: Install GitHub Jenkins plugin. 

Step 1 Go to Manage Jenkins -> Manage Plugin.

Manage Plugin

Step 2 Search Github Plugin in the Available tab then click on Download now and install after the restart.

github plugin

Creating a Jenkins job

Step 1 To Create a new task for Jenkins, click on “New Item” then enter an item name that is suitable for your project and select Freestyle project. Now click Ok. 

Enter item name

Step 2 Select the GitHub project checkbox and set the Project URL to point to your GitHub Repository.

Github project creation

Step 3 Under Source Code Management tab, select Git and then set the Repository URL to point to your GitHub Repository.

GitHub project management

Step 4 Now Under Build Triggers tab, select the “Build when a change is pushed to GitHub” checkbox.

Build triggers

Step 5 At the end, execute Shell script to take a clone from dev. When the configuration is done, click on save button.

Build environment

Configuring GitHub for Jenkins

Step 1 Install the Jenkins (GitHub plugin) on a git repository.

Jenkins (GitHub Plugin)

Step 2 Now set the Jenkins hook URL as the URL for your machine. 

Note: Github will not accept Local URL, hence, we need to install ngrok software to create live URL for port 8080. Here you can find complete guide for configuration: https://ngrok.com/download

Add Jenkins

Phew. That was quite the ride!

Every time you publish changes to GitHub, it will trigger new Jenkins job. Now you know an entire process of continuous integration with Jenkins and GitHub. Similarly, you can integrate Jenkins with selenium to automate testing. Go ahead and try it on your own software development. Note that computers don't get bored so while they handle deployment and testing, you're free to do other important works.

Related: Drupal 8 applications using Drush Aliases

Is there anything you'd like to clarify or see further clarified about Jenkins and GitHub? Let me know in the comments below!

Below given is a presentation on Continuous Integration with Jenkins and GitHub

Selenium: A beginner guide to automation testing tool

Before delving into the how of automation testing using Selenium, let me talk about the why.

Over the past couple of years, the demand for automation has increased at an unprecedented speed and scale as it indispensably minimizes the testing time, eliminate repetitive human tasks and make life easier. The advent of an open source automation testing tools, such as Selenium, has significantly reduced the demand and scope of manual testing.

Needless to say, every testing has its own quirks and best practices! However, there are certain standard best practices that generally apply to most automation, too. Let’s review the best practices of automation testing. You may also like to check out our previous blog post on executing Automation Testing using Selenium.

What is Selenium and why we chose it over other automation testing tools?

Selenium is an extensively used automation tool because of a number of reasons besides being free. The open source tool is supported by a great community and allows QA engineers to write/run test cases in Java, C++, perl, PHP, Python, Ruby, and Scala.

The growing demand of automation industry has persuaded many market leaders to come up with better alternatives. However, all are not open source and free. Check out the list below for the paid automation tools: 

  • TestingWhiz by Cygnet Infotech
  • HP - QTP by HP
  • TestComplete by SmartBear Software
  • Ranorex by Ranorex GmbH

Test cases in Selenium

Implementing test cases in Selenium using Java is not that difficult, but one needs to know how to locate an element in the browser and take required actions.

Locating elements in browser using Selenium

Well, there are several ways we can locate elements in Selenium. Below-mentioned is the most common methods:

  • By ID:
    • Syntax : driver.findElement(By.id(“element id”))
  • By CLASS:
    • Syntax: driver.findElement(By.className("element class"))
  • By NAME:
    • Syntax: driver.findElement(By.name("element name"))
  • By TAGNAME:
    • Syntax: driver.findElement(By.tagName("element html tag name"))
  • By CSS Selector:
    • Syntax: driver.findElement(By.cssSelector("css selector"))
  • By Link:
    • Syntax: driver.findElement(By.link("link text"))
  • By Xpath:
    • Syntax: driver.findElement(By.xpath("xpath expression"))

Xpath

XPath is defined as XML path. In Selenium automation, Xpath is a syntax to find out any element on the web page using HTML DOM structure if the elements are not found by the common locator methods like id, class, name, etc. 

The basic format of XPath is explained below.

Xpath=//tagname[@Attrribute=’value’] 

To use Xpath in Firefox, we need to install FirePath. Currently, FirePath is not supported by Firefox 56 so avoid updating your browser.

Prerequisites:

  • Eclipse IDE
  • JDK 1.7 or more
  • Latest Selenium JAR (3.5.3)

Here I have created a small test case for the demo where the following functionalities are supposed to work.

The test case is to:

  1. Open “http://example.com” in web browser
  2. Enter first name and last name
  3. Click on submit

To open chrome browser through Selenium, you need to download chrome driver from “https://sites.google.com/a/chromium.org/chromedriver/downloads”.

Github link for the complete project: https://github.com/chirag-munjayasara/automation-testing

Creating project to write test case

Following are the major steps involved in creating a project in selenium:

  • Open IDE
  • Launch your own Workspace
  • Create a new JAVAEE project
  • Give project name
  • Click next
  • Click next
  • Click finish

Your project is created. Now you can create java file in the package.

Right-click on the project name -> new -> package. Give package a name and then click finish.

When you will expand your project folder you can see the below structure.

      Project Name
                   Java Resources
                              Src
                                         Package name

                               Libraries

Now create java file to write test cases.

Follow the below steps to create a java file:

  • Right click on package name -> new -> class
  • Give class name (xyz)
  • Click finish

After creating java file, you will see the below directory structure.

      Project Name
                   Java Resources
                              Src
                                         Package name

                                                      xyz.java

                              Libraries

Follow the below steps to add Selenium libraries to the project: 

  • Right click on Src folder
  • Build Path -> Configure Build Path
  • Click on Libraries Folder
  • Click on Add External JARs
  • Select the Selenium JARs that you have download
  • Click Apply and Close.

Selenium library structure

  Project Name
                   Java Resources
                              Src
                                         Package name

                                                      xyz.java

                              Libraries

                                         Referenced Libraries
                                                    Selenium-Server Standalone-3.5.0.jar

Your project is ready. Just write below test case and run in Selenium. :)

Example 1: Here I have used “By.name” to locate text box and “By.id” to locate submit in the browser.

By.name("firstname").sendKeys(‘localtechx’);
By.name("lastname")).sendKeys("Bound");

By.id("submit")).click();

See the screenshot below for an example:

SendKeys
SendKeys is  used to pass value in the text-box.


Use By.id method and perform click operation to locate submit button.


Example: 2 Selecting radio button, checkbox, select option, locate anchor tag and pause the execution.

Following is an example to locate HTML elements by using different methods like By.partialLinkText, By.tagName, By.xpath etc.

Lastly, to generate proper test results and understand the output, we need to use test framework - TestNG - as Selenium test does not generate proper format of test results.

Inspired from JUnit framework, TestNG covers all kind of tests like unit, functional, end-end, integration etc…

Advantages of TestNG over JUnit

  • TestNG annotations are easier to understand when compared to JUnits
  • Generate logs
  • Create an HTML report
  • Dependent method

Installing TestNG in Eclipse (why we need to install in Eclipse and what is the use of it?)

  • In the menu bar, click “Help”
  • Select Eclipse Marketplace option
  • Type TestNG in the dialog box and then press enter
  • Click install
  • New dialog box will pop up, do not change anything and click on confirm
  • Click finish by accepting the license.
  • After installing, Restart the Eclipse.

How to create TestNG project and check whether above-mentioned cases run perfectly or not.
              
Follow the below steps to create TestNG project:

  • Right-click on your package name, you will find the option TestNG
  • Hover it and click on Create TestNG class
  • Select necessary options
  • Click on finish.

Console output

Console output

HTML report

HTML Report

 

testng.xml

To handle multiple test classes, we need to create Testng xml file. After creating TestNG file, configure test run, set test dependency, include or exclude any test, method, class or package and set priority in the xml file.

Follow the below-mentioned steps to create an XML file and run test case:

  • RIght Click on your Java file, you will find the TestNG option.
  • Hover it and now select “Convert to TestNG”.
  • Your testng.xml has been created.
  • Now whenever you want to run your test case, just run this file. This will give you the same output as your .java file.

See the following screenshots for an example:

Convert to TestNGConvert to TestNG step 2

 

Basically, automation testing is an automation of a manual process. In software testing, in fact, it helps to execute pre-scripted tests on an application before its release into production. Though the scope of manual testing is decreasing, it is still prevalent in some of the industries. Testing method totally depends on the project requirement, budget associated with the project, and others.

This is what automation testing is all about.

Now you know the entire process related to automation testing using Selenium. I want to hear from you, which of the testing - automation or manual - have you find most useful? Please share in the comments section below.

Below given is a presentation on automation testing using Selenium.

References:

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch