0% found this document useful (0 votes)
35 views

DevopsLabSCCE

Uploaded by

smgreat1212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

DevopsLabSCCE

Uploaded by

smgreat1212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING

R-22 B.Tech III-I Semester

DEVOPS LAB MANUAL

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

Sl.No Program Page No


1 Write code for a simple user registration form for an event. 4
2 Explore Git and GitHub commands. 6
3 Practice Source code management on GitHub. Experiment with the 12
source code in exercise 1.
4 Jenkins installation and setup, explore the environment. 18
5 Demonstrate continuous integration and development using Jenkins. 27
6 Explore Docker commands for content management. 38
7 Develop a simple containerized application using Docker. 44
8 Integrate Kubernetes and Docker 57
9 Automate the process of running containerized application for exercise 62
7 using Kubernetes.
10 Install and Explore Selenium for automated testing. 68
11 Write a simple program in JavaScript and perform testing using 83
Selenium.
12 Develop test cases for the above containerized application using 85
selenium.

2
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
R22 B.Tech. CSE Syllabus JNTU Hyderabad

CS505PC: DEVOPS LAB

B.Tech. III Year I Sem. L T P C


0 0 2 1
Course Objectives:
 Develop a sustainable infrastructure for applications and ensure high scalability. DevOps aims to
shorten the software development lifecycle to provide continuous delivery with high-quality.

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

1. Write code for a simple user registration form for an event.

Here's an example of a simple user registration form using Flask and Docker
in DevOps:

 Create a Docker file with the following content to create a Docker


image for your Flask application:

FROM python:3.8
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

 Create a requirements.txt file with the following content to list the


dependencies of your Flask application:
Flask==1.1.2

 Create a app.py file with the following code for a simple user
registration form in Flask:

from flask import Flask, request, render_template


app = Flask(__name__)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
password = request.form['password']
# Store the user data in a database or file
return render_template('success.html')

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

Open a web browser and access the registration form at


http://localhost:5000/register.

This example demonstrates how to build a simple user registration form in


Flask and run it in a Docker container in DevOps. Note that this code is only
meant to demonstrate the basic structure of a user registration form and does
not include any security measures or proper error handling. It is highly
recommended to add security measures such as password hashing and
validation before using it in a production environment.

5
Department of Computer Science & Engineering, B.Tech III-I Semester – DEVOPS LAB
EXPERIMENT NO 2

2. Explore Git and GitHub commands.

Aim: To perform Version Control using GIT


Gitis a free and open-source distributed version control system designed to handle everything from
small to very large projects with speed and efficiency. Gitis easy to learn and has a tiny
footprintwithlightning-fastperformance.ItoutclassesSCMtoolslikeSubversion,CVS,Perforce, and
ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.
Some of the basic operations in Git are:

1. Initialize
2. Add
3. Commit
4. Pull
5. Push

Some advanced Git operations are:

1. Branching
2. Merging
3. Rebasing

The following diagram depict the all supported operations in GIT

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

GIT Bash in Windows GIT Shell in Ubuntu

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

Bydefault,wecancreatepublicrepositoryinGitHub.So,wecancopytheentirepublicrepository of any other


users in to own account using “FORK” Operation. Now fork the repository (Sharing with other users
who wants tocontribute).

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.

Afterforkitwillbeaddedinyourlocalrepository.Example,itwilllistalltheuserswhohasforked the code.

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

4.Jenkins installation and setup, explore the environment.


Aim: To install and configure Jenkins to test and deploy Java or Web Applications.

Theory:

To install Jenkins following software packages are required


1) GIT(git-scm.com)
2) Notepad++ (https://notepad-plus-plus.org/downloads/)
3) Latest Java development kit(JDK)
4) Jenkins
5) Apache Maven(Optional)
Step 1-: InstallGIT
Step 2 -: Install Notepad++
Step 3 -: Install Java
Step 4 -: Install Jenkins
Step 5 -: Install Maven

Output:
Step 1: Install GIT

18
Step 2: Install Notepad++

19
Step 3: Install Java

Step 4: Install Jenkins

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.

Aim: To implement Jenkins programming.

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

#list images, jenkins should be available


docker images

dockerps will not show a running container, as we did not yet start it. Start an instance of Jenkins
with the following command:

docker run -p 8080:8080 -p 50000:50000 -v [werjenkinshome]:/var/jenkins_homejenkins/jenkins:lts

Replace [werjenkinshome] with a path fitting for we, e.g. /home/vogella/jenkins_home.

For example, on Windows:

docker run -u 0 -p 8082:8080 -p 50002:50000 -v //C/Users/Lars/jenkins:/var/jenkins_homejenkins/jenkins:lts

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.

 Create a new directory


 Create a file called Dockerfile with the following content:
FROMjenkins/jenkins:lts
27
# if we want to install via apt
USER root
RUN apt-get update && apt-get install-y maven
# drop back to the regular jenkins user - good practice
USERjenkins
 Create a new image with werDockerfile
docker build -t jenkins-maven .

Now we can start wer new image jenkins-maven-latest.

docker run -u 0 -p 8082:8080 -p 50002:50000 -v //C/Users/Lars/jenkins:/var/jenkins_homejenkins-maven:latest

All the configuration and jobs will be stores in wer user defined directory.

2. Using .war file to start Jenkins

Download the jenkins.war file.. From this file we can start Jenkins directly via the command line
with java -jar jenkins*.war.

If we start it locally, we find it running under the following URL: http://localhost:8080/

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

chown tomcat7:nogroup .jenkins

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.

Create an admin user and press Save and Finish.

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.

Assign roles to users

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.

Generate ssh key for Jenkins user

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.

Configure the default port of the Jenkins build server

The default port number can be changed in the config file at

sudo vim /etc/default/jenkins

Here we can set a different port number, e.g. HTTP_PORT=8082

Now we need to restart Jenkins with

29
servicejenkins restart

4. Setting up a Jenkins job


The build of a project is handled via jobs in Jenkins. Select New Item. Afterwards, enter a name for the
job and select Freestyle project and press OK.

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.

Creating a new Pipeline


Click on New Pipeline to create a new Pipeline.

Select wer version control provider.

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,

or with the following command:

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.

Aim: To install and configure Docker tool.

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:

sudo apt update


3. Install PrerequisitePackages
Once we have updated the system, we need to install some necessary packages before
installing Docker. You can do this with the help of a single command:

sudo apt-get install curl apt-transport-https ca-certificates software-properties-common

4. Add the DockerRepositories


Now we have to add the Docker repositories. This will make the installationprocess
much easier. This enables us to use the officially supported method of theinstallation.

First, we add the GPG key, by entering the following command in the command line:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add-


Next, we add the repository:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu


$(lsb_release -cs) stable"
After that, just update the repository information:

sudo apt update

5. Install Docker on Ubuntu18.04


We’re almost done! Use the apt command to installDocker:

sudo apt installdocker-ce

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

with the ID 58118E89F3A912897C070ADBF76221572C52609D from


39
the keyserver hkp://ha.pool.sks-keyservers.net:80 and adds it to the adv keychain.

4. Once we run the command echo "deb https://apt.dockerproject.org/repo ubuntu-


trusty main” | sudo tee /etc/apt/sources.list.d/docker.list we get the following result -

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

7.Develop a simple containerized application using Docker.


Aim:To perform Docker commands with push and pull commands.

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)

(copy below mentioned contents into your Dockerfile)

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.

3. Now if you can see your latest build using ‘dockerimages’command


#docker images

4. Run your new docker-whalebuild


#dockerrundocker-whale

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.

Create a Docker Hub account and repository


1. Signupforadockerhubaccount:Inyourwebbrowser,gototheDocker Hubsignuppage.

2. This account is also valid for dockerstore.

3. Verify your email address and add a newrepository:

4. 4. Learn to ‘tag’ and ‘push’ image to your docker hubaccount.

We will use our docker-whale image to push to docker hub account which you created above.

4.1 Run ‘dockerimages’ command to list allimages

Third columnofaboveoutputshowsyoudockerImageID We

will use this Image ID to tag our docker-whaleimage

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.

5. Push your tagged image to Docker Hub, using the ‘dockerpush’command

6. Go back to the Docker Hub website to see the newly-pushedimage.

7. Pull your new image from dockerhub

7.1 Use ‘dockerimages’ to list all your localimages

7.2 Let’s remove all versions of docker-whale image on our localsystem

45
#dockerrmi -f <Image ID of docker-whale>

Use ‘docker images’ command to confirm if all instances of ‘docker-whale’ has been
removed.

7.3 Now let’s run ‘docker-whale’ and see whathappens.

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.

Step4: Login to the docker hub account

Step5: To push the image with your repository name

Step6: Check the images present, this should include the image name with repository

Step7: Push the image into docker hub account

47
You will see the application generated with the repository name in the docker container

See if build pack demo is listed in docker hub

Step8: Check that the images with the repository is now present in the list

Step9: Pull the image


48
Check it in the browser using the port number assigned.

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

Aim: Develop a simple containerized application using Docker.


Theory:

To create a multi-platform Docker image we need to:


1. Create deployment artifacts (e.g. executable files) for each targetplatform
2. Create a Dockerfile per targetplatform
3. Build a Dockerimage for each targetplatform
4. Push the target platform specific Dockerimage to a Docker registry, e.g.DockerHub
5. Create a multi-platform Dockerimage in the Docker registry based on the individual
target platform Dockerimages

GET THE CODE


git clone https://github.com/callistaenterprise/cadec-2017-service-discovery
cd cadec-2017-service-discovery\go-quotes\

BUILD A DOCKER IMAGE FOR WINDOWS

Compile the Go source code to an executable for Windows:

set GOOS=windows
go build -o quotes-windows-amd64.exe

Try out the Windows executable without using Docker:

50
./quotes-windows-amd64.exe

It should startup and say something like:

Starting ML Go version of quote-service on port 8080


2017/12/19 16:23:17 Starting ML HTTP service at 8080

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 ."...

Stop the program with CTRL/C.

Ensure that your “Docker for Windows” runs Windows containers. enter the command:

docker info

Look for the field OSType, it should say windows.

If not, switch to Windows containers using the Docker menu:

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"]

Build the Docker image and push it to DockerHub:

docker build -f Dockerfile-windows-amd64 -t magnuslarsson/quotes:24-go-windows-amd64 .


docker push magnuslarsson/quotes:24-go-windows-amd64

You can start the Windows specific Docker image with:

docker run -d -p 8080:8080 --name quotes magnuslarsson/quotes:24-go-windows-amd64

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!

Stop the Windows container with the command:

dockerrm -f quotes

BUILD A DOCKER IMAGE FOR LINUX

Compile the Go source to an executable for Linux:

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"]

Build the Docker image and push it to DockerHub:

docker build -f Dockerfile-linux-amd64 -t magnuslarsson/quotes:24-go-linux-amd64 .


docker push magnuslarsson/quotes:24-go-linux-amd64

You can start the Linux specific Docker image with:

docker run -d -p 8080:8080 --name quotes magnuslarsson/quotes:24-go-linux-amd64

Now, try out the service using curl:

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!

Stop the Linux container with the command:

dockerrm -f quotes

BUILD A MULTI-PLATFORM DOCKER IMAGE

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).

The manifest file, manifest-quotes-multi-platform.yml, looks like:

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

The multi-platform Docker image is create with the command:

./manifest-tool-darwin-amd64 --username=magnuslarsson --password=xxx push from-spec


manifest-quotes-multi-platform.yml> **Note:** `./manifest-tool-darwin-amd64` requires

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:

docker run --rmmplatform/mquerymagnuslarsson/quotes:24-go

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:

TRY OUT THE MULTI-PLATFORM DOCKER IMAGE

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:

docker run -d -p 8080:8080 --name quotes magnuslarsson/quotes:24-go

55
Test it using curl:

curlhttp://localhost:8080/api/quote -UseBasicParsing

Verify that the operatingSystem field in the response has the value linux!

Kill the Linux container:

dockerrm -f quotes

Switch “Docker for Windows” to use Windows containers:

Start a Windows container:

docker run -d -p 8080:8080 --name quotes magnuslarsson/quotes:24-go

Test it using curl:

curlhttp://192.168.1.224:8080/api/quote -UseBasicParsing

Verify that the operatingSystem field in the response now has the value windows!

Wrap up with killing the Windows container:

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

8. Integrate Kubernetes and Docker

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.

3. Verify your Kubernetes cluster


If you’ve worked with Docker before, you’re used to managing containers with
the docker and docker-compose command lines. Kubernetes uses a different tool called kubectl to
manage apps - Docker Desktop installs kubectl for you too.

Check the state of your Docker Desktop cluster:

kubectl get nodes


You should see a single node in the output called docker-desktop. That’s a full Kubernetes cluster,
with a single node that runs the Kubernetes API and your own applications.

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.

4. Run a familiar application


Let’s run the classic Docker sample voting app! It’s a distributed application which uses a
Postgres database and Redis message queue, with application components running in Python,
.NET and Node.js containers.

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):

kubectl apply -f https://raw.githubusercontent.com/docker/docker-birthday/master/resources/kubernetes-docker-


desktop/vote.yaml
It’ll take a couple of minutes for all the container images to download from Docker Hub and start
up.

5. Check the app components


Kubernetes runs containers for you, so instead of explicitly running them with docker container run,
you describe the desired outcome in a YAML file and when you run kubectl apply Kubernetes
starts all the containers.

Containers in Kubernetes are wrapped in another object called a pod. Have a look at the pods for
the voting app:

kubectl -n vote get pods


You should see lots of pods, with names starting db-, redis- etc. When the READY column
says 1/1 for every pod, that means all the containers are running.

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.

6. Use the app


Browse to http://localhost:5000 and you should see the classic voting application:

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.

Browse to http://localhost:5001 and you’ll see the results:

60
That’s a Node.js app which reads the data from Postgres. Everything is running in containers
through Kubernetes.

7. Check the resilience


Kubernetes makes sure containers are running to keep your app at the service level you requested
in the YAML file. They’re all Docker containers which you can also manage with
the docker command line.

Print the container ID for the result app:

docker container ls -f name='k8s_result*' --format '{{.ID}}'


And now remove that container:

docker container rm -f $(docker container ls -f name='k8s_result*' --format '{{.ID}}')


Check back on the result app in your browser at http://localhost:5001 and you’ll see it’s still
working. Kubernetes saw that the container had been removed and started a replacement straight
away.

Print the result container ID again:

docker container ls -f name='k8s_result*' --format '{{.ID}}'


And you’ll see it’s a new container. Kubernetes makes sure the running app always matches the
desired state in the application YAML file.

61
EXPERIMENT No.9

9. Automate the process of running containerized application for exercise


7 using Kubernetes.

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:

> curl -Lo minikube


https://storage.googleapis.com/minikube/releases/v0.12.2/minikube-darwin-
amd64
> chmod +x minikube
> sudo mv minikube /usr/local/bin/
Install kubectl
Kubectl is a command line application that executes commands against
Kubernets clusters. Instructions for installing kubectl are available here.

> curl -Lo kubectl http://storage.googleapis.com/kubernetes-


release/release/v1.3.0/bin/darwin/amd64/kubectl
> chmod +x kubectl
> sudo mv kubectl /usr/local/bin/
Set up a Docker repository
Kubernetes pulls container images from publicly available registries. But
because we are building an application that we will not be publishing to public
docker registries, we need to create a local registry. There is a great write up on
how to set up a local docker registry at Newstack.

Start minikube with the registry


62
Now that we have a local docker registry, we can go ahead and tell minikube to
consume images from this registry. However, if you have started a minikube
cluster previously, the registry override will not be available to it unless it is
deleted.

> docker-machine ip registry


192.168.99.100
> minikube stop
> minikube delete
> minikube start --vm-driver="virtualbox" --insecure-
registry=192.168.99.100:80
Create a container image for the application
The application in this case is a simple Spring Boot application that has exactly
one controller.

@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.

> eval $(docker-machine env dev)


> mvn package docker:build
Tag and push the image to local registry
The generated image sadiqueio/hello-world need to be published to the local
registry we created.

> docker tag sadiqueio/hello-world 192.168.99.100:80/hello-world


> docker push 192.168.99.100:80/hello-world
Define and create a service
We will define a Kubernetes service object for this application
hello-world-service.yaml:

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:

> kubectl create -f hello-world-service.yaml


You have exposed your service on an external port on all nodes in your
cluster. If you want to expose this service to the external internet, you may
need to set up firewall rules for the service port(s) (tcp:30194) to serve traffic.

See http://releases.k8s.io/release-1.3/docs/user-guide/services-firewalls.md for


more details.
service "hello-world" created
Make a note of the port assigned to this service. We will use this port later to
access our application.

Define and create a deployment


The next step is to define and create a deployment for our application. This is
where we specify the image we previously created and published to the registry.

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.

> curl -s http://192.168.99.102:30194/hello | jq .


{
"message": "hello"
}

67
EXPERIMENT No.10

10.Install and Explore Selenium for automated testing.

Aim: To perform continuous testing of web applications using Selenium.

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.

Continuous means undisrupted testing done on a continuous basis. In a Continuous DevOps


process, a software change (release candidate) is continuously moving from Development to
Testing to Deployment.

Selenium

Selenium is an open-source tool which automates web browser testing. It is mainly used for
functional (unit testing & regression testing).

Reasons for considering Selenium (advantages):

1. Programming Language support – Selenium scripts can be written in major programming


languages like Java, Python, Perl, Php, Ruby and C#.
2. Web Browser support – Support cross browser testing on chrome, Firefox, internet explorer
and safari.
68
3. Operating Systems support – Selenium can be used on Widows, Mac or Linux.

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

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="seleniumContinuousTesting"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->

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

java -cpbin;lib/* org.testng.TestNG testing.xml

Step 4: Build Jenkins jobs by executing the batch file


Step 4.1: Install Jenkins and setup Jenkins by referring the below guide
https://www.jenkins.io/doc/book/installing/windows/

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

Step 5.3: Go the Jenkins Dashboard 🡪 Manage Jenkins 🡪 Configure Systems

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.

Step 5.8: Go to the Project 🡪 Select Build Now

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

AIM: Write a simple program in JavaScript and perform testing using


Selenium
<!DOCTYPE html>
<html>
<head>
<title>Simple JavaScript Program</title>
</head>
<body>
<p id="output">0</p>
<button id="increment-button">Increment</button>
<script>
const output = document.getElementById("output");
const incrementButton =
document.getElementById("increment-button");
let count = 0;
incrementButton.addEventListener("click", function() {
count += 1;
output.innerHTML = count;
});
</script>
</body>
</html>

 Write a test case for this program 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 {
83
private WebDriver driver;
@Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
}
@Test
public void testIncrementButton() {
driver.get("file:///path/to/program.html");
driver.findElement(By.id("increment-button")).click();
String result = driver.findElement(By.id("output")).getText();
assert result.equals("1");
}

@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

You might also like