SlideShare una empresa de Scribd logo
1 de 20
What is unit testing
Arthur Freyman
golovast@gmail.com
www.mindend.com
What is unit testing
• Break down the project into small pieces
• Test them independently
What is unit testing + devops
• Infrastructure testing (AWS, Openstack, Azure, etc)
• Configuration management (Ansible, Chef, Puppet, Salt)
• Scripts/tools
• Other products
Why write them?
• Larger teams/complex systems
• Future proofing (somewhat)
• The rest of the organization.
• Test your logic
When to write them?
• Better as you go. More difficult later
• Tons of formal systems
– TDD
– BDD
– ATDD
• Your code will be better.
Examples (Python)
• AWS script example:
import boto.ec2
def create_instance(options, region, key, sec_groups, subnets):
conn = boto.ec2.connect_to_region(region)
try:
reservation = conn.run_instances(image_id=options.OS,
security_group_ids=sec_groups, subnet_id=subnets,
instance_type=options.size, min_count=options.Count,
max_count=options.Count, key_name=key, dry_run=False)
return reservation
except Exception as e:
print “Couldn’t launch instance because of:”
print e
Examples (Python)
• Unit test example:
import create_instance
import unittest
from moto import mock_ec2
args = {}
sec_groups = ‘sg-1234’
subnets = None
args.Key = ‘test_key’
args.Size = ‘t3.medium’
args.Count = 1
args.OS = ‘ami-1234’
@mock_ec2
def test_create_instance():
conn = boto.ec2.connect_to_region(‘us-west-1’)
create_instance(args, ‘us-west-1’, args.Key, sec_groups, subnets)
reservations = conn.get_all_instances()
assert len(reservations) == 1
Examples (Python)
• Mocks – when resource unavailable, unsuitable, slow, etc.
• Stub – kind of like a mock, but can’t verify methods. Usually
canned answers.
• Fake – Class that implements an interface but has fixed data
and no logic.
Examples (Python)
• Script:
import os
dir_path = "/tmp/"
file_name = "text.txt"
def search_for_file(dir_path, file_name):
file_list = []
for f in os.listdir(dir_path):
if os.path.isfile(os.path.join(dir_path, f)) and f == file_name:
file_list.append(file_name)
if not file_list:
return “not found”
else:
return file_name
search_and_remove_file(dir_path, file_name)
Examples (Python)
• Unit Test Example:
import search_and_remove_file
import unittest
from mock import patch
dir_path = "/tmp/"
file_name = "text.txt"
class MyTests (unittest.TestCase):
def test_file_found(self):
with patch('os.listdir', return_value=['text2.txt']):
test_value = search_for_file(dir_path,file_name)
self.assertEqual(test_value, file_name)
def test_not_found(self):
with patch('os.listdir', return_value=['text4.txt']):
test_value = search_for_file(dir_path,file_name)
self.assertEqual(test_value, "not found")
if __name__ == '__main__':
unittest.main()
Examples (Shell)
• I am not going to do it. 
– But check out bats (https://github.com/sstephenson/bats) if you have
to do it. Also roundup and shunit2.
Examples (Ansible)
• Version your roles and maybe playbooks.
• Design your workflow
– Branching
– Builds
• Test your expectations
– Files
– Services
– Packages
– Users
– Multiple variations.
Examples (Ansible)
• Keep the roles/manifests/cookbooks/states small
– Unix philosophy – do one thing and do it well
– Keep it modular
– DRY
• Some java app
– Bad: single role for configuring the system, installing prereqs and pushing the app
– Good:
• Role/jvm
• Role/tomcat
• Role/users
• Role/sys_config
• Role/code_deploy
Examples (Ansible)
• Complex role/cookbook/manifest/state
• Nginx as an example:
– Could install with different modules (compiled and defaults)
– From source/package
– Different versions
– Default sites with different configurations (proxy, etc)
• Validate as much as you can.
– Especially complex conditionals.
– Templating engines
– Multiple sets of testing vars
Examples (Ansible + Friends)
• Ansible-lint (https://github.com/willthames/ansible-lint)
– Defaults are good, but add your own things.
• Syntax check
– Ansible-playbook –syntax-check –list-tasks –i ‘127.0.0.1’ test.yml
• Assert module
• Serverspec, inspec, rolespec, testinfra, goss, chefspec,
ansible_spec, test-kitchen
• Test playbooks
Examples (Ansible + Friends)
• Template validations (native tools)
vars:
- validate_conf: /usr/sbin/named-checkconf
tasks:
- name: install named.conf
action: tempalte src=named.conf.j2 dest=/etc/named.conf validate = ‘{{ validate_conf }} %s’
• Other validators:
– /usr/bin/nginx –t –c nginx.conf
– Apachectl configtest
– /usr/sbin/sshd –t
– /usr/sbin/squid -k check
– /usr/libexec/mysqld --defaults-file=/root/test-my.cnf --verbose --help 1>/dev/null
– syslogd -f /etc/rsyslog.testing.conf -d
Examples (Ansible + Friends)
• Testinfra
def nginx_present(Package):
nginx = Package(“nginx”)
assert nginx.is_installed
def nginx_running_enabled(Service):
nginx = Service(“nginx”)
assert nginx.is_running
assert nginx.is_enabled
Examples (Ansible + Friends)
• Serverspec
describe user(‘nginx’) do
it { should exist }
it { should belong_to_group ‘nginx’}
end
describe process(‘nginx’) do
it { should be_running }
its(:user) { should eq ‘nginx’ }
end
describe port (80) do
it { should be_listening }
end
describe “Server Configuration” do
it ‘should response with right status code’ do
uri = URI(‘http://localhost’)
http = Net::HTTP.new(uri.host)
request = Net::HTTP::Get.new(uri)
response = http.request(request)
expect(response.code).to eq(‘200’)
end
end
Examples (Ansible + Friends)
• Goss – new tool, written in go.
– Builds yaml files (sort of automatically)
– ‘goss autoadd nginx’
package:
nginx:
installed: true
versions:
- 1.4.1-3ubuntu1.3
nginx = Package(“nginx”)
assert nginx.is_installed
service:
nginx:
enabled:true
running:false
The End

Más contenido relacionado

La actualidad más candente

Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introMaurice De Beijer [MVP]
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Samyak Bhalerao
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slidesericholscher
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Holger Grosse-Plankermann
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JSMichael Haberman
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHPvinaikopp
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Plone Testing Tools And Techniques
Plone Testing Tools And TechniquesPlone Testing Tools And Techniques
Plone Testing Tools And TechniquesJordan Baker
 
Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Sam Becker
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010Timo Stollenwerk
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking FrameworksDror Helper
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Model-Driven Testing For Agile Teams
Model-Driven Testing For Agile TeamsModel-Driven Testing For Agile Teams
Model-Driven Testing For Agile TeamsKerryKimbrough
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidMatthew Johnson
 
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014istefo
 

La actualidad más candente (20)

PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Plone Testing Tools And Techniques
Plone Testing Tools And TechniquesPlone Testing Tools And Techniques
Plone Testing Tools And Techniques
 
Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking Frameworks
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Model-Driven Testing For Agile Teams
Model-Driven Testing For Agile TeamsModel-Driven Testing For Agile Teams
Model-Driven Testing For Agile Teams
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue Kid
 
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
(Unit) Testing in Emberjs – Munich Ember.js Meetup July 2014
 

Similar a Unit testing presentation

Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott Nottingham
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott NottinghamAutomated Puppet Testing - PuppetCamp Chicago '12 - Scott Nottingham
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott NottinghamPuppet
 
Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2nottings
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing DaeHyung Lee
 
Py.test
Py.testPy.test
Py.testsoasme
 
20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasaggarrett honeycutt
 
Introduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release updateIntroduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release updateAlex Pop
 
Apache ant
Apache antApache ant
Apache antkoniik
 
Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Thibaud Desodt
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
Containers: The What, Why, and How
Containers: The What, Why, and HowContainers: The What, Why, and How
Containers: The What, Why, and HowSneha Inguva
 
ARGUS - THE OMNISCIENT CI
ARGUS - THE OMNISCIENT CIARGUS - THE OMNISCIENT CI
ARGUS - THE OMNISCIENT CICosmin Poieana
 
Developing IT infrastructures with Puppet
Developing IT infrastructures with PuppetDeveloping IT infrastructures with Puppet
Developing IT infrastructures with PuppetAlessandro Franceschi
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in SeoulJongwook Woo
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suiteericholscher
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...Yevgeniy Brikman
 
DevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopDevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopMandi Walls
 
Reality-Driven Testing using TestContainers
Reality-Driven Testing using TestContainersReality-Driven Testing using TestContainers
Reality-Driven Testing using TestContainersOleksii Holub
 

Similar a Unit testing presentation (20)

Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott Nottingham
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott NottinghamAutomated Puppet Testing - PuppetCamp Chicago '12 - Scott Nottingham
Automated Puppet Testing - PuppetCamp Chicago '12 - Scott Nottingham
 
Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2
 
Learning Puppet basic thing
Learning Puppet basic thing Learning Puppet basic thing
Learning Puppet basic thing
 
Py.test
Py.testPy.test
Py.test
 
20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag
 
Introduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release updateIntroduction to InSpec and 1.0 release update
Introduction to InSpec and 1.0 release update
 
Apache ant
Apache antApache ant
Apache ant
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Unit tests = maintenance hell ?
Unit tests = maintenance hell ?
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Containers: The What, Why, and How
Containers: The What, Why, and HowContainers: The What, Why, and How
Containers: The What, Why, and How
 
ARGUS - THE OMNISCIENT CI
ARGUS - THE OMNISCIENT CIARGUS - THE OMNISCIENT CI
ARGUS - THE OMNISCIENT CI
 
Developing IT infrastructures with Puppet
Developing IT infrastructures with PuppetDeveloping IT infrastructures with Puppet
Developing IT infrastructures with Puppet
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
DevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopDevOpsDays InSpec Workshop
DevOpsDays InSpec Workshop
 
Reality-Driven Testing using TestContainers
Reality-Driven Testing using TestContainersReality-Driven Testing using TestContainers
Reality-Driven Testing using TestContainers
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Unit testing presentation

  • 1. What is unit testing Arthur Freyman golovast@gmail.com www.mindend.com
  • 2. What is unit testing • Break down the project into small pieces • Test them independently
  • 3. What is unit testing + devops • Infrastructure testing (AWS, Openstack, Azure, etc) • Configuration management (Ansible, Chef, Puppet, Salt) • Scripts/tools • Other products
  • 4. Why write them? • Larger teams/complex systems • Future proofing (somewhat) • The rest of the organization. • Test your logic
  • 5. When to write them? • Better as you go. More difficult later • Tons of formal systems – TDD – BDD – ATDD • Your code will be better.
  • 6. Examples (Python) • AWS script example: import boto.ec2 def create_instance(options, region, key, sec_groups, subnets): conn = boto.ec2.connect_to_region(region) try: reservation = conn.run_instances(image_id=options.OS, security_group_ids=sec_groups, subnet_id=subnets, instance_type=options.size, min_count=options.Count, max_count=options.Count, key_name=key, dry_run=False) return reservation except Exception as e: print “Couldn’t launch instance because of:” print e
  • 7. Examples (Python) • Unit test example: import create_instance import unittest from moto import mock_ec2 args = {} sec_groups = ‘sg-1234’ subnets = None args.Key = ‘test_key’ args.Size = ‘t3.medium’ args.Count = 1 args.OS = ‘ami-1234’ @mock_ec2 def test_create_instance(): conn = boto.ec2.connect_to_region(‘us-west-1’) create_instance(args, ‘us-west-1’, args.Key, sec_groups, subnets) reservations = conn.get_all_instances() assert len(reservations) == 1
  • 8. Examples (Python) • Mocks – when resource unavailable, unsuitable, slow, etc. • Stub – kind of like a mock, but can’t verify methods. Usually canned answers. • Fake – Class that implements an interface but has fixed data and no logic.
  • 9. Examples (Python) • Script: import os dir_path = "/tmp/" file_name = "text.txt" def search_for_file(dir_path, file_name): file_list = [] for f in os.listdir(dir_path): if os.path.isfile(os.path.join(dir_path, f)) and f == file_name: file_list.append(file_name) if not file_list: return “not found” else: return file_name search_and_remove_file(dir_path, file_name)
  • 10. Examples (Python) • Unit Test Example: import search_and_remove_file import unittest from mock import patch dir_path = "/tmp/" file_name = "text.txt" class MyTests (unittest.TestCase): def test_file_found(self): with patch('os.listdir', return_value=['text2.txt']): test_value = search_for_file(dir_path,file_name) self.assertEqual(test_value, file_name) def test_not_found(self): with patch('os.listdir', return_value=['text4.txt']): test_value = search_for_file(dir_path,file_name) self.assertEqual(test_value, "not found") if __name__ == '__main__': unittest.main()
  • 11. Examples (Shell) • I am not going to do it.  – But check out bats (https://github.com/sstephenson/bats) if you have to do it. Also roundup and shunit2.
  • 12. Examples (Ansible) • Version your roles and maybe playbooks. • Design your workflow – Branching – Builds • Test your expectations – Files – Services – Packages – Users – Multiple variations.
  • 13. Examples (Ansible) • Keep the roles/manifests/cookbooks/states small – Unix philosophy – do one thing and do it well – Keep it modular – DRY • Some java app – Bad: single role for configuring the system, installing prereqs and pushing the app – Good: • Role/jvm • Role/tomcat • Role/users • Role/sys_config • Role/code_deploy
  • 14. Examples (Ansible) • Complex role/cookbook/manifest/state • Nginx as an example: – Could install with different modules (compiled and defaults) – From source/package – Different versions – Default sites with different configurations (proxy, etc) • Validate as much as you can. – Especially complex conditionals. – Templating engines – Multiple sets of testing vars
  • 15. Examples (Ansible + Friends) • Ansible-lint (https://github.com/willthames/ansible-lint) – Defaults are good, but add your own things. • Syntax check – Ansible-playbook –syntax-check –list-tasks –i ‘127.0.0.1’ test.yml • Assert module • Serverspec, inspec, rolespec, testinfra, goss, chefspec, ansible_spec, test-kitchen • Test playbooks
  • 16. Examples (Ansible + Friends) • Template validations (native tools) vars: - validate_conf: /usr/sbin/named-checkconf tasks: - name: install named.conf action: tempalte src=named.conf.j2 dest=/etc/named.conf validate = ‘{{ validate_conf }} %s’ • Other validators: – /usr/bin/nginx –t –c nginx.conf – Apachectl configtest – /usr/sbin/sshd –t – /usr/sbin/squid -k check – /usr/libexec/mysqld --defaults-file=/root/test-my.cnf --verbose --help 1>/dev/null – syslogd -f /etc/rsyslog.testing.conf -d
  • 17. Examples (Ansible + Friends) • Testinfra def nginx_present(Package): nginx = Package(“nginx”) assert nginx.is_installed def nginx_running_enabled(Service): nginx = Service(“nginx”) assert nginx.is_running assert nginx.is_enabled
  • 18. Examples (Ansible + Friends) • Serverspec describe user(‘nginx’) do it { should exist } it { should belong_to_group ‘nginx’} end describe process(‘nginx’) do it { should be_running } its(:user) { should eq ‘nginx’ } end describe port (80) do it { should be_listening } end describe “Server Configuration” do it ‘should response with right status code’ do uri = URI(‘http://localhost’) http = Net::HTTP.new(uri.host) request = Net::HTTP::Get.new(uri) response = http.request(request) expect(response.code).to eq(‘200’) end end
  • 19. Examples (Ansible + Friends) • Goss – new tool, written in go. – Builds yaml files (sort of automatically) – ‘goss autoadd nginx’ package: nginx: installed: true versions: - 1.4.1-3ubuntu1.3 nginx = Package(“nginx”) assert nginx.is_installed service: nginx: enabled:true running:false

Notas del editor

  1. Practice of writing separate code to help determine if there are errors. What kind of errors can you catch? Syntax, logical. Unit can be an entire module, single class or function or anything else. Make sure your thing works under a given set of conditions. Helps with refactoring. Unit tests vs functional tests. Expected output, given known input. Different from functional tests, which capture user requirements.
  2. Practice of writing separate code to help determine if there are errors. What kind of errors can you catch? Syntax, logical. Unit can be an entire module, single class or function or anything else. Make sure your thing works under a given set of conditions. Helps with refactoring. Unit tests vs functional tests. Expected output, given known input. Different from functional tests, which capture user requirements.
  3. Make sure your code works under a given set
  4. Larger team and if complex system, it allows to work on the project together in an easier way. I may not know what the other guy is doing or maybe he left. I can feel more comfortable modifying something if there is a good test for it. We all forget shit. It helps to modify things later. Be considerate of future us who will have to maintain and debug this code months or even years down the line. Somewhat impress the developer organizations. Show that you follow similar practices and pay attention to code quality.
  5. Better do it as you’re writing a tool or a script or a role. You can do it later, but it’s a pain in the ass. TDD focuses on the implementation. Write the test first. BDD is behavioral aspect system. Given that the user is logged in when the user clicks on X, we should see Y. ATDD focuses on capturing reqs in accpetance tests and focuses more on external factors. If you can’t figure out how to test something, maybe it’s a code smell and you should refactor. Loose coupling. Your code will be more modular.
  6. Very simple use case where you spin up an instance in EC2 with some options. Maybe a part of a larger script or a tool or API or whatever. Yes, I know it’s using boto (not boto3, which you should be).
  7. Unittest framework, but there are many others. Nose (extension to unittest), pytest and so on. Lives in the same repo. Python decorator (won’t get into those right now).
  8. Unittest framework, but there are many others. Lives in the same repo. Python decorator (won’t get into those right now).
  9. Unittest framework, but there are many others. Lives in the same repo. Python decorator (won’t get into those right now).
  10. Some debate about ansible and what and when needs to be tested.
  11. Some debate about ansible and what and when needs to be tested.
  12. Many different ways of doing it. Lint is a form of a unit/functional test. Syntax checking is always helpful. Writing test playbooks is a good thing.