DevopsLabSCCE
DevopsLabSCCE
ENGINEERING
1
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Department of Computer Science & Engineering
B.Tech III-I Semester
DEVOPS LAB
2
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
R22 B.Tech. CSE Syllabus JNTU Hyderabad
Course Outcomes:
1. Understand the need of DevOps tools
2. Understand the environment for a software application development
3. Apply different project management, integration and development tools
4. Use Selenium tool for automated testing of application
List of Experiments:
1. Write code for a simple user registration form for an event.
2. Explore Git and GitHub commands.
3. Practice Source code management on GitHub. Experiment with the source code in exercise 1.
4. Jenkins installation and setup, explore the environment.
5. Demonstrate continuous integration and development using Jenkins.
6. Explore Docker commands for content management.
7. Develop a simple containerized application using Docker.
8. Integrate Kubernetes and Docker
9. Automate the process of running containerized application for exercise 7 using Kubernetes.
10. Install and Explore Selenium for automated testing.
11. Write a simple program in JavaScript and perform testing using Selenium.
12. Develop test cases for the above containerized application using selenium.
TEXT BOOKS:
1. Joakim Verona., Practical DevOps, Packt Publishing, 2016.
REFERENCE BOOKS:
Deepak Gaikwad, Viral Thakkar. DevOps Tools from Practitioner's Viewpoint. Wileypublications.
1.
2. Len Bass, Ingo Weber, Liming Zhu. DevOps: A Software Architect's Perspective. Addison Wesley.
3
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
EXPERIMENT NO 1
Here's an example of a simple user registration form using Flask and Docker
in DevOps:
FROM python:3.8
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]
Create a app.py file with the following code for a simple user
registration form in Flask:
return render_template('register.html')
if __name__ == '__main__':
app.run(host='0.0.0.0')
Create an templates folder and add the following two files:
register.html and success.html.
4
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
register.html
<form method="post">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Submit">
</form>
success.html
<h2>Registration Successful</h2>
Build the Docker image for your Flask application using the
following command: docker build -t simple-flask-app .
Run a Docker container from the image using the following
command: docker run -p 5000:5000 simple-flask-app
5
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
EXPERIMENT NO 2
1. Initialize
2. Add
3. Commit
4. Pull
5. Push
1. Branching
2. Merging
3. Rebasing
6
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Installation of GIT
1. In windows, download GIT from https://git-scm.com/ and perform
the straight forward installation.
2. In Ubuntu, install GIT using $sudo apt install git, Confirm the version after installation using
command $git–version
Once installation is done, open the terminal in Ubuntu and perform the following steps or in windows
Right click and select Git bash here.
The output of GIT Bash in windows and GIT shell in Ubuntu is shown below
7
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
8
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
9
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Creating new repository and selecting public option followed by create repository
10
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Login with another account→Copy and Paste URL of repository→thenjustclick on fork to clone to
others account. Suppose we want to fork public repository “timetracker”. So, search for “timetracker”
github repository on google and once its opened clicked on “Fork button” from the top of the github
web page as shownbelow.
To delete the repository, open the desired repository you want to delete and go to the settings option.
There you will see delete repository button to delete it.
11
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Now, if you want to download a repository in local machine, then git clone command is used
followed by path to repository. In GitHub the path of repository can be known through clone or
download button and it can be downloaded using git clone command as shown below.
Conclusion:
Git, is a powerful tool that can improve code development and documentation. Ultimately, the
complexityofaVCSnotonlygivesusersawell-documented“undo”buttonfortheiranalyses,but it also
allows for collaboration and sharing of code on a massive scale. Furthermore, it does not need to be
learned in its entirety to be useful. Instead, you can derive tangible benefits from
adoptingversioncontrolinstages.Withafewcommands(gitinit,gitadd,gitcommit),youcan
start tracking your code development and avoid a file system full of copied file. Lastly, by forking
public repositories and sending pull requests, you can directly improve scientific software.
12
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
EXPERIMENT NO 3
3.Practice Source code management on GitHub. Experiment with the source code in
exercise 1
Aim:To perform version control on websites/software’s using GIT with push and pull
commands.
Theory:
First open Github.com and create a new account.After verifying account through
E- mail, create a Repository on github.com
Pull and Push Processes The pull command used to fetch the repository from github to
local while push is used to commit files from local repository to Github.
Push → Push changes to Web repository
Pull → Pull changes to Local repository
Push:
13
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
14
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Pull:
15
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Fetch:
16
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
Before committing changes in index.html
Conclusion:
Adding a few additional commands (git push, git clone, git pull) and a GitHub account, you
can share your code online, transfer your changes across machines, and collaborate in small
groups.
Lab outcome:
ITL803.1: Remember the importance of DevOps tools used in software development life cycle.
ITL803.3: Examine the different Version Control Strategies.
17
EXPERIMENT NO 4
Theory:
Output:
Step 1: Install GIT
18
Step 2: Install Notepad++
19
Step 3: Install Java
20
21
Step 5: Configuration and Jenkins Pipeline
22
Step 6: Creation of job using Jenkins
23
Step 7: Build maven project using Jenkins
24
25
CONCLUSION:
Thus, we have installed and configure Jenkins to test and deploy Java or Web Applications.
26
EXPERIMENT NO 5
5.Demonstrate continuous integration and development using Jenkins.
Theory:
“Continuous Integration is a software development practice where members of a team
integratetheirworkfrequently,usuallyeachpersonintegratesatleastdaily-leadingtomultiple
integrationsperday.Eachintegrationisverifiedbyanautomatedbuild(includingtest)todetect
integration errors as quickly as possible.” In simple way, Continuous integration (CI) is the
practice of frequently building and testing each change done to your code automatically.
Jenkins is a self-contained, open source automation server which can be used to automate all
sorts of tasks related to building, testing, and delivering or deploying software. Our first job
will execute the shell commands. The freestyle project provides enough options and features
to build the complex jobs that you will need in yourprojects.
OUTPUT:
1. Installation in a Docker container
docker pull jenkins/jenkins:lts
dockerps will not show a running container, as we did not yet start it. Start an instance of Jenkins
with the following command:
If we need other tools installed, we can create wer own Docker file with the necessary tooling
installed. For example the following creates a new image based on Jenkins with Maven installed.
All the configuration and jobs will be stores in wer user defined directory.
Download the jenkins.war file.. From this file we can start Jenkins directly via the command line
with java -jar jenkins*.war.
To run it in wer Tomcat server, put the .war file into the webapps directory. If we start Tomcat,
wer Jenkins installation will be available under
http://localhost:8080/jenkins
If the jenkins.war is deployed in wer webapps directory, but can not be started and the tomcat
manager says FAIL - Application at context path /jenkins could not be started, we may need to
grant the permissions for JENKINS_HOME.
sudomkdir .jenkins
sudo
3. Configure Jenkins
After installation, open a browser and connect to it. The default port of Jenkins is :8080,
therefore on wer local machine we find it under the following URL:
http://localhost:8080/
We will need to copy the initial password from the file system of the server.
Afterwards we can select to install Plugins. Select the Install suggested Plugins to get a typical
configuration.
Select Manage Jenkins and then Configure Global Security. Select the Enable security flag. The
easiest way is to use Jenkins own user database. Create at least the user "Anonymous" with read
access. Also create entries for the users we want to add in the next step.
28
On the login page, select Create an account to create the users we just gave access.
If we want to create a role based authorization Strategy we first need to install the Role-based
Authorization Strategy Plugin. Go to Manage Jenkins Manage Plugins Available enter Role-
based Authorization Strategy in the filter box and select and install the Plugin. To see a list of
commonly used Plugins go to Plugin management.
Now go to Manage Jenkins Manage and Assign Roles Assign Roles to grant users additional
access rights.
Navigate to Manage Roles to define access restrictions in detail. Pattern is a regex value of the job
name. The following grants unregistered users read-only access to wer build jobs that start with
the L-, C-, I- or M- and only those.
If we want to access a private Git repo, for example at GitHub, we need to generate an ssh key-
pair. Create a SSH key with the following command.
sudo -u jenkinsssh-keygen
The public key must be uploaded to the service we are using, e.g., GitHub.
29
servicejenkins restart
Enter a description for the job (project name) and configure how many builds should be retained and for
how long.
Configure how the source code can be retrieved. If we are for example using Git, enter the URL to the Git
repository. If the repository is not public, we may also need to configure the credentials.
Specify when and how wer build should be triggered. The following example polls the Git
repository every 15 min. It triggers a build, if something has changed in the repo.
30
To trigger a build after a commit on the Git repository, select GitHub hook trigger for GITScm
polling instead of Poll SCM.
Press Save to finish the job definition. Press Build Now on the job page to validate that the job
works as expected.
31
After a while the job should go to green or blue (depending on wer configuration), if successful.
Click on the job and afterwards on Console Output to see the log file. Here we can analyze the
build errors.
5. Build Pipelines
Jenkins pipelines help we align the build process of a project. This is done by specifying tasks
and the order in which they are executed. There are all kinds of possible tasks that a Jenkins
pipeline can do for we. For example, build assets, send an email on error, send the build artifacts
via SSH to wer application server, etc.
Jenkins allows to specify pipelines using a Jenkinsfile. This is just a textfile that contains the
necessary data for Jenkins to execute the pipeline.
Jenkins supports two different syntaxes.
1. Declarative (since Pipeline version 2.5)
2. Scripted
For this tutorial we will focus on the declarative approach.
The following example shows a pipeline with 2 stages:
pipeline{
agent any
stages{
stage('Build Assets'){
agent any
steps{
echo'Building Assets...'
}
}
stage('Test'){
agent any
steps{
echo'Testing stuff...'
}
}
}
}
The agent directive tells Jenkins to allocate a workspace and an executor for the pipeline. Without it, the
32
pipeline is not valid and therefore required.
Setup using the Blue Ocean Plugin
The above process can also be done using the Blue Ocean Jenkins Plugin.
To install the Plugin go to Manage Jenkins Manage Plugins Available and select the Blue
Ocean Plugin.
After the installation is finished we have an additional menu entry called Open Blue Ocean in
wer main Jenkins navigation.
33
Depending on wer provider we will need to pass some kind of credentials.
The Blue Ocean application will provide a link to the GitHub page we need to visit. The necessary
permissions that Blue Ocean needs to operate are already selected. Add a description and click
on Generate Token at the bottom of the page.
Copy the generated token and paste it in the Blue Ocean mask.
Select the account the repository belongs to and select the repository.
Adding steps to wer Pipeline
In the next screen we will see a visual representation of wer Pipeline. Here we can add or remove steps.
34
35
To create a new step click on + in the canvas. A menu will open on the right that lets we specify
a name and what steps we want to perform.
After we have finished editing the Pipeline Blue Ocean will offer we to commit the newly
created pipeline to wer repository.
Under the hood Blue Ocean only created a valid Jenkinsfile to be used by Jenkins.
After committing Jenkins will build the project using the newly modified Pipelines.
36
6. Restart wer Jenkins
After installing Plugins we will need to restart Jenkins. We can do so by adding restart as URL
parameter,
servicejenkins restart
CONCLUSION:
Here, we got to learn about the Jenkins Programming and how to install and configure it.
37
EXPERIMENT NO 6
6.Explore Docker commands for content management.
Theory:
1. Access YourVPS
First, we have to connect to the server using SSH. If you’re having trouble, check out
our PuTTY tutorial.
2. Update YourSystem
Then, the system needs to be updated to make it safer and reliable for the Docker
installation. Run the following two commands:
First, we add the GPG key, by entering the following command in the command line:
6. Check DockerStatus
Once the installation is complete, it is a good idea to check the status of the service.
38
Output:
1. When we run the sudo apt-get update command, we will get the following result –
2. Once we run the command sudo apt-get install apt-transport-https ca-certificates we get
the following result.
3. The next step is to add the new GPG key. The following command will download the key
5. Next, we issue the apt-get update command to update the packages on the Ubuntu system.
6. To verify that the package manager is pointing to the right repository, you can do it by issuing
the apt-cache command.
40
7. Issue the apt-get update command to ensure all the packages on the local system are up
to date.
8. We have to install the linux-image-extra-* kernel packages, which allows one to use
the aufs storage driver. It can be done by using the following command.
sudo apt-get install linux-image-extra-$(uname -r)
linux-image-extra-virtual
41
9. The final step is to install Docker and we can do this with the following command − sudo
apt-get install –y docker-engine
10. To see the version of Docker running, you can issue the following command − docker
version
42
11. To see more information on the Docker running on the system, you can issue the
following command − docker info
Conclusion: By following all the steps we got to learn, how to install docker in ubuntu and
configure the same.
43
EXPERIMENT NO 7
Theory:
To Build your own Docker Image
1. Write a dockerfile
#mkdirmydockerbuild(create a directory named mydockerbuild)#cd mydockerbuild(go to
directory created above)#vi Dockerfile(create a new dockerfile using vi editor)
FROM docker/whalesay:latest
RUN apt-get -y update && apt-get install -y fortunes
CMD /usr/games/fortune -a | cowsay
2. Build dockerimage
#docker build -t docker-whale .
If you see ‘no permission’ error, try to prefix above command with ‘sudo’ as shown in above
snapshot.
If you are programmer or in some way related to coding or software world, I assume that you
must be aware of GitHub. Similarly, there exists DockerHub.
What is DockerHub?
People all over the world create Dockerimages. You can find these images by browsing the
Docker Hub. In this next section, you’ll search for and find the image you’ll use in the rest of
this getting started.
44
What is Docker Store?
The Docker Store contains images from individuals like you and official images from
organisationslike RedHat, IBM, Google, Microsoft, and a whole lot more. Each image
repository contains information about an image.
We will use our docker-whale image to push to docker hub account which you created above.
Third columnofaboveoutputshowsyoudockerImageID We
4.2 Tag the ‘docker-whale’ image using the ‘docker tag’ command and the imageID.
#dockertag <image-id of docker-whale><your dockerhubusername>/docker-whale:latest
Now if your use ‘docker images’ command to list images, you shall see your dockerhub
username against docker-whale image as shown in above snapshot.
45
#dockerrmi -f <Image ID of docker-whale>
Use ‘docker images’ command to confirm if all instances of ‘docker-whale’ has been
removed.
When you use ‘dockerrun’ it automatically downloads (pulls) images that don’t yet exist
locally, creates a container, and starts it. Use the following command to pull and run the
‘docker-whale’ image, substituting your Docker Hub username.
Output:
Step 1. Create a docker Hub account
Step2: Build a demo application my-python-app by running the following commands in
command prompt
46
Till now we have create the my-python-app file
See if the file is working in the browser using port number
Step3: See all the images present in the docker. Here you will see that my-python-app is also
present.
Step6: Check the images present, this should include the image name with repository
47
You will see the application generated with the repository name in the docker container
Step8: Check that the images with the repository is now present in the list
Conclusion:
Built docker image with the help of python and then learned about the usage of docker image
push to share our images to the Docker Hub registry and also how to pull an image.
49
EXPERIMENT NO 7
set GOOS=windows
go build -o quotes-windows-amd64.exe
50
./quotes-windows-amd64.exe
Open another “Windows PowerShell” terminal window and try out the service using curl:
curlhttp://localhost:8080/api/quote -UseBasicParsing
Expected response:
StatusCode : 200
StatusDescription : OK
Content
{"hardwareArchitecture":"amd64","operatingSystem":"windows","ipAddress":"4d131b511ab9/f
e80::9846:5be3:c0bb:2d91%Ethernet172.24.224.172","quote":"In Go, the code does exactly
what it says on the page ."...
Ensure that your “Docker for Windows” runs Windows containers. enter the command:
docker info
The Dockerfile for building the Windows Docker image, Dockerfile-windows-amd64, looks like:
51
FROM microsoft/nanoserver
EXPOSE 8080
ADD quotes-windows-amd64.exe /
ENTRYPOINT ["./quotes-windows-amd64.exe"]
The current version of “Docker for Windows” has a limitation that prevents access ports
published by containers using localhost, e.g. curlhttp://localhost:8080/api/quote does not work.
For details, see https://blog.sixeyed.com/published-ports-on-windows-containers-dont-do-
loopback/.
Instead, we can use the PC’s IP address. You can use ipconfig to get the IP address.
E.g.:
curlhttp://192.168.1.224:8080/api/quote -UseBasicParsing
Expect a similar response as from the curl command above. Verify that operatingSystem field
has the value windows!
dockerrm -f quotes
set GOOS=linux
go build -o quotes-linux-amd64
52
Switch to Linux containers using the Docker menu:
The Dockerfile for building the Linux Docker image, Dockerfile-linux-amd64, looks like:
FROM scratch
EXPOSE 8080
ADD quotes-linux-amd64 /
ENTRYPOINT ["./quotes-linux-amd64"]
curlhttp://localhost:8080/api/quote -UseBasicParsing
Expected response:
StatusCode : 200
StatusDescription : OK
53
Content
:{"hardwareArchitecture":"amd64","operatingSystem":"linux","ipAddress":"0c4e0824f479/172.1
7.0.2","quote":"I like a lot of the design decisions they made in the [Go] language. Basically, I
like all oft...
Verify that the operatingSystem field now has the value linux!
dockerrm -f quotes
Now, it’s time to combine the two platform specific Docker images into one common Docker
image.
We will use the standalone tool manifest-tool. Executables can be downloaded from:
https://github.com/estesp/manifest-tool/releases.
I used version v0.7.0 of the tool compiled for macOS (I got stuck on some strange authentication
problem when trying out the Windows version).
image: magnuslarsson/quotes:24-go
manifests:
-
image: magnuslarsson/quotes:24-go-linux-amd64
platform:
architecture: amd64
os: linux
-
image: magnuslarsson/quotes:24-go-windows-amd64
platform:
architecture: amd64
os: windows
54
macOS, you can however try out the Windows version (or a Linux version) on your own.
Verify that we now have a Docker image for our Go service that supports both Linux
andWindows:
Expected response:
Image: magnuslarsson/quotes:24-go
* Manifest List: Yes
* Supported platforms:
- linux/amd64
- windows/amd64:10.0.14393.1944
You can also take a look into DockerHub to see the resulting three Docker images, e.g. in my
case: https://hub.docker.com/r/magnuslarsson/quotes/tags/
Expected result:
Now we should be able to run our Go service in both Windows and Linux containers using one
and the same Docker image: magnuslarsson/quotes:24-go!
Since we currently have “Docker for Windows” configured to run Linux containers, let’s start
with trying it out on Linux:
55
Test it using curl:
curlhttp://localhost:8080/api/quote -UseBasicParsing
Verify that the operatingSystem field in the response has the value linux!
dockerrm -f quotes
curlhttp://192.168.1.224:8080/api/quote -UseBasicParsing
Verify that the operatingSystem field in the response now has the value windows!
dockerrm -f quotes
Conclusion:
I have learned how to create a Docker image that works on different hardware architectures and
operating systems. I Have also created a Docker image based on a service written in Go and package
it for use in both Linux and Windows on 64 bit Intel based hardware.
56
EXPERIMENT No.8
Enable Kubernetes
Kubernetes itself runs in containers. When you deploy a Kubenetes cluster you first install
Docker (or another container runtime like containerd) and then use tools like kubeadm which
starts all the Kubernetes components in containers. Docker Desktop does all that for you.
Make sure you have Docker Desktop running - in the taskbar in Windows and the menu bar on
the Mac you’ll see Docker’s whale logo. Click the whale and select Settings:
A new screen opens with all of Docker Desktop’s configuration options. Click
on Kubernetes and check the Enable Kubernetes checkbox:
57
That’s it! Docker Desktop will download all the Kubernetes images in the background and get
everything started up. When it’s ready you’ll see two green lights in the bottom of the settings
screen saying Docker running and Kubernetes running.
The star in the screenshot shows the Reset Kubernetes Cluster button, which is one of the
reasons why Docker Desktop is the best of the local Kubernetes options. Click that and it will
reset your cluster back to a fresh install of Kubernetes.
The Kubernetes components are running in Docker containers, but Docker Desktop doesn’t show
them by default to keep things simple when you’re running docker commands.
Try:
docker container ls
and you’ll see zero containers (unless you have some of your own running).
But try:
58
docker info
And you’ll see a whole bunch of containers in the running state (18 on my machine), which are
the various parts of Kubernetes.
All the components of the app are published in public images on Docker Hub. All you need to
run it is a Kubernetes manifest - a YAML files which describes all the components of the app.
Here’s the voting app definition in Kubernetes which you’ll be deploying (compare it to
the voting app definition in Docker Compose if you want to see how Kubernetes is different):
Containers in Kubernetes are wrapped in another object called a pod. Have a look at the pods for
the voting app:
You can have many containers in one pod in Kubernetes, and they share the same network
and compute environment. That lets you do very cool things with the sidecar pattern.
59
That’s a Python application running in a Docker container, being managed by Kubernetes. Click
on Cats (or Dogs) and the app sends a message to the Redis message queue. That message gets
picked up by a .NET worker application, which updates a Postgres database.
60
That’s a Node.js app which reads the data from Postgres. Everything is running in containers
through Kubernetes.
61
EXPERIMENT No.9
Install minikube
Minikube is a tool that makes it easy to run Kubernetes for local development.
To run minikube, you need to have a virtualizer installed - in my case I already
had VirtualBox installed. Instructions for installing minikube is available here.
In my case, this is what I did:
@RestController
public class HelloController {
@RequestMapping("/hello")
public Map hello() {
return singletonMap("message", "hello");
}
}
In order to create a docker container from this application, we will use the
Maven Docker Plugin. We will need to set a prefix for our docker image. This
can be done with this maven property:
<docker.image.prefix>sadiqueio</docker.image.prefix>
This plugin expects a Dockerfile to be present in the src/main/docker directory.
Our Dockerfile will look like this:
63
FROM frolvlad/alpine-oraclejdk8:slim
ADD hello-world-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENTRYPOINT ["java","-jar","/app.jar"]
With this in place, we can generate a docker image. We need to ensure that we
are looking at the dev docker host.
apiVersion: v1
kind: Service
metadata:
name: hello-world
labels:
app: hello-world
tier: backend
spec:
type: NodePort
ports:
# the port that this service should serve on
64
- port: 8080
selector:
app: hello-world
tier: backend
The service can be created using:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: hello-world
spec:
replicas: 1
template:
metadata:
labels:
65
app: hello-world
tier: backend
spec:
containers:
- name: hello-world
image: 192.168.99.100:80/hello-world
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 8080
> kubectl create -f hello-world-deployment.yaml
deployment "hello-world" created
Ensure that the deployment is successful
> kubectl get services
NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hello-world 10.0.0.252 <none> 8080/TCP 4m
> kubectl get deployments
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
hello-world 1 1 1 1 4m
Access the service
We already know the port assigned to our service. Because we specified type:
NodePort, the IP address we need to use is that of the Kubernetes cluster. This
IP address can be found using the minikube command.
> minikube ip
66
192.168.99.102
Now that we have both pieces of information, we can test that our application is
up.
67
EXPERIMENT No.10
Theory:
Continuous Testing is the process of executing automated tests as part of the software delivery
pipeline in order to obtain feedback on the business risks associated with a software release
candidate as rapidly as possible. It evolves and extends test automation to address the increased
complexity and pace of modern application development and delivery.
Continuous Testing in DevOps is a software testing type that involves testing the software at
every stage of the software development life cycle. The goal of Continuous testing is evaluating
the quality of software at every step of the Continuous Delivery Process by testing early and
testing often. The continuous testing process in DevOps involves stakeholders like Developer,
DevOps, QA and
The old way of testing was hand off centric. The software was handed off from one team to
another. A project would have definite Development and QA phases. QA teams always wanted
more time to ensure quality. The goal was that the quality should prevail over project schedule.
However, business wants faster delivery of software to the end user. The newer is the software,
the better it can be marketed and increase revenue potential of the company. Hence, a new way of
testing was evolved.
Selenium
Selenium is an open-source tool which automates web browser testing. It is mainly used for
functional (unit testing & regression testing).
In this practical, we would use Selenium for creating test cases, TestNG for getting detailed
report of those test cases and further we use Jenkins to run our test cases. Jenkins will see if our
test cases are getting passed and if those test cases fail’s we would receive an email notification.
And this is how we complete the process of continuous testing in DevOps.
Test Case: Automate amazon.in search and Facebook login. And at the end, receive a mail
confirmation if the test result fail. This whole process has to be automated and in continuous
manner for continuous testing.
Steps for Demonstration:
Step 1: Create Test cases with Selenium on Eclipse IDE.
Step 1.1: Download Selenium standalone-3.9.0.jar and Selenium server-3.9.0.zip files from the
link below and unzip the file.
https://selenium-release.storage.googleapis.com/index.html?path=3.9/
Step 1.2: Download latest Java as a prerequisite for Eclipse followed by installation of Eclipse.
Step 1.3: Launch the Eclipse IDE and open Eclipse Marketplace to install TestNG plugin.
Step 1.4: Restart Eclipse IDE and create a new java project under New 🡪 Project 🡪 Java Project
and Select JRE 1.8 under “Use Execution Environment for JRE”
69
Step 1.5: Now add new package from File Tab.
Step 1.6: Select Project 🡪 Click New 🡪 Class and Click Finish and enter the below code
package<Package name>;
importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.chrome.ChromeDriver;
70
public class <File name> {
public void JenkinsTest() {
System.setProperty("webdriver.chrome.driver","file_location");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.amazon.in");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Nike shoes");
driver.findElement(By.xpath("/html/body/div[1]/header/div/div[1]/div[3]/div/form/div[2]/div/inp
ut")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().back();
String title = driver.getTitle();
System.out.println("Page Title is:-" + title);
driver.navigate().to("https://www.facebook.com");
driver.findElement(By.name("email")).sendKeys("[email protected]");
driver.findElement(By.name("pass")).sendKeys("1234");
driver.findElement(By.id("loginbutton")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.quit();
}
}
71
Step 1.7: Select Project 🡪 Properties 🡪 Java Build Path 🡪 Select Add External JARs and Select
all the Jar files in the unzipped Selenium Jar files also in Lib folder and Selenium standalone jar
file. Apply changes
72
Step 1.8: Select and right click Project 🡪 Properties 🡪 Java Build Path 🡪 Select Add Library and
Select TestNG and click on Finish
Step 2:Converting into XML files for executing TestNG test suite.
Step 2.1: Select and right click on Class file 🡪TestNG🡪 Convert to TestNG and type the below
code in Preview
73
Step 2.2: Open command prompt and change the working directory to the eclipse workspace and
enter the command
java -cp C:\Users\SHWETA\eclipse workspace\Selenium\bin;C:\Users\SHWETA\eclipse-
workspace\Selenium\lib\* org.testng.TestNG testng.xml
Test Result: (Explanation: A new chrome browser opens up and automatically open amazon.in
and enter nike shoes in the search bar and then navigates back again and then open facebook.com
and login with email: [email protected] and password: 1234 and hit Login. This has been coded
in the class file)
74
75
Step 3: Create windows batch file
Create a Text Document and Type the command below and create a bat file with Save as file
name as shown below to create a Windows batch file
Step 4.2: Create a new Freestyle project on Jenkins by browsing to localhost:8080 or whichever
port has been assigned to Jenkins during the installation.
76
Step 4.3: Under General Section 🡪 Tab on Advanced and Select the checkbox “Use custom
workspace” and in the Directory Form Fill enter the workspace location of Eclipse project
Step 4.4: Under Build Section 🡪 Select “Add build step” button 🡪 Select Execute Windows
batch command and in Post-build Actions Section 🡪 Select Add “post-build action” 🡪 Select
“Email notification” and add your email address in the Recipients field. Finally, click on Apply
and Save buttons.
77
Step 5: Schedule Jobs & configure email notification
Step 5.1: Go the Jenkins Dashboard 🡪 Manage Jenkins 🡪 Manage Plugins 🡪 Search Email
Extension Template 🡪 click on the checkbox and click on Install without restart.
Step 5.2: Turn On “Less Secure app access” of your google account, in order to receive mails
78
Step 5.4: Scroll down to E-mail Notification section at the bottom and add the details as shown
below
Step 5.5: Click on Test configuration by sending test e-mail, Enter mail address in Test e-mail
recipient and hit Test Configuration Button.
79
Step 5.6: Check the test mail in your Gmail inbox
Step 5.7: Go to the Dashboard 🡪 Select the project 🡪 Select Configure 🡪 Build Trigger Section
🡪 Select Build periodically checkbox and Enter the Schedule details in cron format
H 10 * * *
Meaning: In the morning 10 on every date of every month and every day of the week.
80
Step 5.9: Click on the Build Number “#3” in my case 🡪 click on console output
Step 5.10: Verify email notification feature by creating an error by commenting any line in class
file under your project in Eclipse IDE
Step 5.11: Check your Gmail Inbox for failed Test Case mail
81
Conclusion:
We have successfully completed the task of executing continuous testing with the help of
Selenium to build test cases, TestNG to create testing.xml file so that we can integrate Jenkins for
continuous testing on specified time intervals and receive email notification if the test cases fail.
82
EXPERIMENT NO.: 11. Write a simple program in JavaScript and
perform testing using Selenium
@After
public void tearDown() {
driver.quit();
}
}
You can run the test case using the following command:
$ javac Main.java
$ java Main
The output of the test case should be:
.
Time: 0.189
OK (1 test)
This output indicates that the test case passed, and the increment button was
successfully clicked, causing the output to be incremented by 1.
84
EXPERIMENT NO.: 12.Develop test cases for the above containerized application using
selenium
AIM: Develop test cases for the above containerized application using selenium
Here is an example of how you could write test cases for the containerized
application using Selenium
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class Main {
private WebDriver driver;
@Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
MRITS Page 22
Downloaded by 11785 Aravind Kumar N ([email protected])
lOMoARcPSD|37614292
III-II B-TECH CSE (AIML)
DEVOPS LAB MANUAL
}
@Test
public void testHomePageLoads() {
driver.get("http://localhost:8080");
String title = driver.getTitle();
assert title.equals("My Containerized Application");
}
@Test
public void testSubmitForm() {
driver.get("http://localhost:8080");
driver.findElement(By.name("name")).sendKeys("John Doe");
driver.findElement(By.name("email")).sendKeys("[email protected]
85
m");
driver.findElement(By.name("submit")).click();
String result = driver.findElement(By.id("result")).getText();
assert result.equals("Form submitted successfully!");
}
@After
public void tearDown() {
driver.quit();
}
}
You can run the test cases using the following command:
$ javac Main.java
$ java Main
The output of the test cases should be:
..
Time: 1.135
OK (2 tests)
This output indicates that both test cases passed, and the containerized
application is functioning as expected.
86