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

DevNet Associate -Code Review and Testing

The document outlines the importance and process of code reviews in software development, emphasizing the benefits of feedback from multiple reviewers to enhance code quality. It details various types of code reviews, such as formal, change-based, and over-the-shoulder reviews, along with the significance of testing, including unit and integration testing. Additionally, it introduces Test-Driven Development (TDD) as a methodology that integrates testing into the software development process from the outset.

Uploaded by

crio1q
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DevNet Associate -Code Review and Testing

The document outlines the importance and process of code reviews in software development, emphasizing the benefits of feedback from multiple reviewers to enhance code quality. It details various types of code reviews, such as formal, change-based, and over-the-shoulder reviews, along with the significance of testing, including unit and integration testing. Additionally, it introduces Test-Driven Development (TDD) as a methodology that integrates testing into the software development process from the outset.

Uploaded by

crio1q
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

7/23/24, 8:59 AM DevNet Associate -Code Review and Testing

3.3.9 Branching Features


Show Menu
 / Software Development and Design / Code Review and Testing

3.3.10 .diff Files Development and


Software
3 
Design

3.3.11
Lab - Software Version Control
with Git
Code Review and Testing
3.4 Coding Basics  3.5.1

3.4.1
Methods, Functions, Modules, and What is a Code Review and Why Should You Do This? 
Classes

3.4.2 Clean Code


A code review is when developers look over the codebase, a subset of code, or specific code changes and
provide feedback. These developers are often called reviewers. It is better to have more than one reviewer when
3.4.3 Methods and Functions possible.

It is best to have reviewers who understand the purpose of the code so that they can give quality and relevant
3.4.4 Modules
feedback. The reviewers will provide comments, typically to the author of the code, on what they think needs to be
fixed. Because a lot of comments can be subjective, it is up to the author to decide if the comment needs to be
3.4.5 Classes addressed, but it is good to have agreement from the reviewer(s) if it will not be fixed. This code review process
only happens after the code changes are complete and tested.

3.4.6 Lab - Explore Python Classes


The goal of code reviews is to make sure that the final code:

is easy to read
3.5 Code Review and Testing 
is easy to understand
follows coding best practices
What is a Code Review and Why
3.5.1 uses correct formatting
Should You Do This?
is free of bugs
has proper comments and documentation

 DevNet Associate
3.5.2 Types of Code Reviews
 is clean
v1.0

3.5.3 Testing Doing code reviews has benefits for the whole team. For the author, they get input from the reviewers and learn
additional best practices, other ways the code could have been implemented, and different coding styles. As a
3.5.4 Unit Testing result of the review, the author learns from their mistakes and can write better code the next time. Code reviews
aren’t just for junior developers, they are a great learning process for all developers.

3.5.5 Integration Testing Code reviews also transfer knowledge about the code between developers. If the reviewers have to work on that
piece of code in the future, they will have a better understanding of how it works.
3.5.6 Test-Driven Development (TDD)
Code reviews are a way to refine working code or spot potential bugs, which increases the quality of the code. In
general, having another set of eyes on the code is never a bad thing.
3.5.7 Lab - Create a Python Unit Test

3.6 Understanding Data Formats 


3.5.2
Software Development and
3.7 
Design Summary
Types of Code Reviews 

Understanding and Using


4 
APIs

5 Network Fundamentals 

Application Deployment and


6 
Security

Infrastructure and
7 
Automation

Cisco Platforms and


8 
Development

https://contenthub.netacad.com/devnet/3.5.1 1/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing

3.3.9 Branching Features Code is sent to Reviewers Comments are


Show Menu Code Author reviewers Code Reviewers provide Comments sent to the author
comments
3.3.10 .diff Files Development and
Software
3 
Design If additional comments are
Lab - Software Version Control made by reviewers
3.3.11
with Git
If the reviewers approve the
changes
3.4 Coding Basics  Fixed code gets
Fixed Code Comments Author sent to Fixed code Reviewers
reviewers
Methods, Functions, Modules, and
3.4.1
Classes
Final code Author
3.4.2 Clean Code

Author addresses comments and make code


3.4.3 Methods and Functions changes

There are many ways to do code reviews. Each one has its own benefits. The most common types of code review
3.4.4 Modules processes include:

3.4.5 Classes Formal code review


Change-based code review
Over-the-shoulder code review
3.4.6 Lab - Explore Python Classes Email pass-around

Formal Code Review


3.5 Code Review and Testing 

A formal code review is where developers have a series of meetings to review the whole codebase. In this
What is a Code Review and Why
3.5.1 meeting, they go over the code line by line, discussing each one in detail. This type of code review process
Should You Do This?
promotes discussion between all of the reviewers.

3.5.2 Types of Code Reviews


A formal code review enables reviewers to reach a consensus, which may result in better feedback. You might do
a new code review every time the comments are addressed.
3.5.3 Testing
Details of the code review meetings, such as the attendees, the comments, and comments that will be addressed,
are documented. This type of code review is often called Fagan inspection and is common for projects that use the
3.5.4 Unit Testing
waterfall software development methodology.

3.5.5 Integration Testing A modern adaptation of the formal code review is to have a single meeting to review only the code changes. This
way, the code can benefit from the live discussion amongst reviewers. This is sometimes known as a walkthrough.

3.5.6 Test-Driven Development (TDD)


Change-Based Code Review

3.5.7 Lab - Create a Python Unit Test A change-based code review, also known as a tool-assisted code review, reviews code that was changed as a
result of a bug, user story, feature, commit, etc.

3.6 Understanding Data Formats  In order to determine the code changes that need to be reviewed, a peer code review tool that highlights the code
changes is typically used. This type of code review is initiated by the developers who made the code changes and
Software Development and are responsible for addressing the agreed upon comments. In this type of code review process, the reviewers
3.7
Design Summary 
usually perform the review independently and provide the comments via the peer code review tool.

A change-based code review makes it easy to determine the actual code changes to be reviewed and enables
Understanding and Using
4  multiple reviewers to get a diverse look into the code.
APIs

Over-the-Shoulder Code Review

5 Network Fundamentals 
An over-the-shoulder code review is exactly what it sounds like. A reviewer looks over the shoulder of the
developer who wrote the code. The developer who wrote the code goes through the code changes line by line and
Application Deployment and the reviewer provides feedback.
6 
Security
With this method, if the fix is not difficult, the code may be changed on the spot so that the reviewer can re-review
it immediately. The benefit of an over-the-shoulder code review is that there is direct interaction between the
Infrastructure and author of the code and the reviewer, which allows for discussion about what is the right fix. The downside of this
7 
Automation type of code review is that it typically involves only one reviewer, so the comments can be one-sided.

Email Pass-Around
Cisco Platforms and
8 
Development
An email pass-around review can occur following the automatic emails sent by source code management systems
when a checkin is made. When the emails are sent, it is up to the other developers to review the code changes

https://contenthub.netacad.com/devnet/3.5.1 2/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing
that were made in that checkin. The downside of this type of code review is that sometimes a single checkin can
be just a piece of the whole code change, so it may not include the proper context to fully understand the code
changes.
3.3.9 Branching Features
Show Menu

3.3.10 .diff Files Development and


Software
3  3.5.3
Design

3.3.11
Lab - Software Version Control Testing 
with Git

3.4 Coding Basics  Why do coders test software? The simple answer is to make sure it works the way it is supposed to work. This
answer conceals a wealth of nuance and detail.
Methods, Functions, Modules, and
3.4.1
Classes To begin with, software testing is classically subdivided into two general categories:

3.4.2 Clean Code Functional testing seeks to determine whether software works correctly. Does it behave as intended in a logical
sense, from the lowest levels of detail examined with Unit Testing, to higher levels of complexity explored in
Integration Testing?
3.4.3 Methods and Functions
Non-functional testing examines usability, performance, security, resiliency, compliance, localization, and many
other issues. This type of testing finds out if software is fit for its purpose, provides the intended value, and
3.4.4 Modules minimizes risk.

3.4.5 Classes You might think that functional testing happens early in the development cycle, and non-functional testing begins
after parts of the software are built or even finalized. This is incorrect. Some types of non-functional testing (for
example, determining whether a particular language, open source library, or component meets requirements of a
3.4.6 Lab - Explore Python Classes design, or a standard) need to happen well before design is fixed.

"Agile" software development favors highly-adaptable, minimally-planned creation and extension of a Minimum
3.5 Code Review and Testing 
Viable Product (MVP) over short sprints. This means the product exists, in some form, from very early on in the
process. And that means it can be subject both to functional and non-functional tests from the start.
What is a Code Review and Why
3.5.1
Should You Do This?
In fact, as you’ll see towards the end of this unit, some developers advocate using testing as a framework for
guiding software development. This means capturing design requirements as tests, then writing software to pass
3.5.2 Types of Code Reviews
those tests. This is called Test-Driven Development (TDD).

3.5.3 Testing Let’s look at some methods and tools for testing the lines of code, blocks, functions, and classes.

3.5.4 Unit Testing

3.5.5 Integration Testing 3.5.4

Unit Testing 
3.5.6 Test-Driven Development (TDD)

3.5.7 Lab - Create a Python Unit Test Detailed functional testing of small pieces of code (lines, blocks, functions, classes, and other components in
isolation) is usually called Unit Testing. Modern developers usually automate this kind of testing using unit test
frameworks. These test frameworks are software that lets you make assertions about testable conditions and
3.6 Understanding Data Formats 
determine if these assertions are valid at a point in execution. For example:

Software Development and


3.7
Design Summary  a = 2 + 2
assert a == 4

Understanding and Using


4  The assert keyword is actually native to Python. In this case, the assertion will return true because 2 + 2 does, in
APIs
fact, equal 4. On the other hand, if you were to have:

5 Network Fundamentals  assert a == 5

Application Deployment and It would return false and trigger an error.


6 
Security
Collecting assertions and reporting on tests is made easier with testing frameworks. Some examples of test
frameworks for Python include:
Infrastructure and
7 
Automation unittest — This is a framework included in Python by default. It lets you create test collections as methods
extending a default TestCase class.
PyTest — This is a framework that is easily added to Python (from pip repositories: pip3 install pytest ).
Cisco Platforms and
8  PyTest can run unittest tests without modification, but it also simplifies testing by letting coders build tests as
Development
simple functions rather than class methods. PyTest is used by certain more-specialized test suites, like PyATS
from Cisco.

https://contenthub.netacad.com/devnet/3.5.1 3/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing
Both are used in this part, so you can see some of the differences between them.

Simple Unit Testing with PyTest


3.3.9 Branching Features
Show Menu PyTest is handy because it automatically executes any scripts that start with test or end with _test.py , and within
those scripts, automatically executes any functions beginning with `test or tests`. So we can unit test a piece of
3.3.10 .diff Files Development and
Software code (such as a function) by copying it into a file, importing pytest, adding appropriately-named testing functions
3 
Design (names that begin with tests ), saving the file under a filename that also begins with tests_, and running it with
Lab - Software Version Control PyTest.
3.3.11
with Git
Suppose we want to test the function add5() , which adds 5 to a passed value, and returns the result:
3.4 Coding Basics 
def add5(v):
Methods, Functions, Modules, and myval = v + 5
3.4.1
Classes return myval

3.4.2 Clean Code


We can save the function in a file called tests_mytest.py . Then import pytest and write a function to contain our
tests, called tests_add5() :
3.4.3 Methods and Functions

# in file tests_mytest.py
3.4.4 Modules import pytest
def add5(v):
myval = v + 5
3.4.5 Classes
return myval
def tests_add5():
3.4.6 Lab - Explore Python Classes r = add5(1)
assert r == 6
r = add5(5)
3.5 Code Review and Testing  assert r == 10
r = add5(10.102645)
What is a Code Review and Why assert r == 15.102645
3.5.1
Should You Do This?

The tests in our testing function use the standard Python assert keyword. PyTest will compile and report on those
3.5.2 Types of Code Reviews
results, both when collecting test elements from the file (a preliminary step where PyTest examines Python's own
code analysis and reports on proper type use and other issues that emerge prior to runtime), and while running the
3.5.3 Testing tests_add5() function.

You can then run the tests using:


3.5.4 Unit Testing

pytest tests_mytest.py
3.5.5 Integration Testing

And get a result that looks something like this:


3.5.6 Test-Driven Development (TDD)

============================= test session starts ==============================


3.5.7 Lab - Create a Python Unit Test
platform darwin -- Python 3.8.1, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /home/tana/python/mytest
collected 1 item
3.6 Understanding Data Formats 
tests_mytest.py . [100%]
============================== 1 passed in 0.01s ===============================
Software Development and
3.7
Design Summary 
Note that while the function under test is certainly trivial, many real-world programs contain functions that, like this
one, perform math on their arguments. Typically, these functions are called by higher-level functions, which then
Understanding and Using
4  do additional processing on the returned values.
APIs
If there is a mistake in a lower-level function, causing it to return a bad result, this will likely be reflected in higher-
level output. But because of all the intermediary processing, it might be difficult or impossible to find the source of
5 Network Fundamentals  an error (or even note whether an error occurred) by looking at output of these higher-level functions, or at
program output in general.

Application Deployment and


6  That is one reason why detailed unit testing is essential for developing reliable software. And it is a reason why unit
Security
tests should be added, each time you add something significant to code at any level, and then re-run with every
change you make. We recommend that, when concluding a work session, you write a deliberately-broken unit test
Infrastructure and as a placeholder, then use a start-of-session unit test run to remind you where you left off.
7 
Automation
Simple Unit Testing with unittest

Cisco Platforms and The unittest framework demands a different syntax than PyTest. For unittest , you need to subclass the built-in
8 
Development TestCase class and test by overriding its built-in methods or adding new methods whose names begin with
test_ . The example unit test script, above, could be modified to work with unittest like this:

https://contenthub.netacad.com/devnet/3.5.1 4/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing

import unittest
def add5(v):
myval = v + 5
3.3.9 Branching Features return myval
Show Menu
class tests_add5(unittest.TestCase):
3.3.10 .diff Files Development and
Software def test_add5(self):
3  self.assertEqual(add5(1),6)
Design
self.assertEqual(add5(5),10)
Lab - Software Version Control
3.3.11 self.assertEqual(add5(10.102645),15.102645)
with Git
if __name__ == '__main__':
unittest.main()
3.4 Coding Basics 

As with PyTest, you import the unittest module to start. Your function follows.
Methods, Functions, Modules, and
3.4.1
Classes
To subclass the TestCase class, pass it to your own (derived) test class (again called tests_add5 , though this is
now a class, rather than a function), causing the latter to inherit all characteristics of the former. For more on
3.4.2 Clean Code
Python object-oriented programming (OOP), see the documentation.

3.4.3 Methods and Functions Next, use unittest's assertEqual method (this is one of a wide range of built-in test methods) in the same way that
you used Python's native assert in the PyTest example. Basically, you are running your function with different
arguments, and checking to see if returned values match expectations.
3.4.4 Modules

The last stanza is a standard way of enabling command-line execution of our program, by calling its main function;
3.4.5 Classes which, in this case, is defined by unittest.

Save this file (again as tests_mytest.py ), ensure that it is executable (for example, in Linux, using chmod +x
3.4.6 Lab - Explore Python Classes
tests_mytest.py ) and execute it, adding the -v argument to provide a verbose report:

3.5 Code Review and Testing  python3 tests_mytest.py -v

What is a Code Review and Why


3.5.1
Should You Do This? test_add5 (__main__.tests_add5) ... ok
----------------------------------------------------------------------
3.5.2 Types of Code Reviews Ran 1 test in 0.000s
OK

3.5.3 Testing

3.5.4 Unit Testing

3.5.5
3.5.5 Integration Testing
Integration Testing 

3.5.6 Test-Driven Development (TDD)

3.5.7 Lab - Create a Python Unit Test After unit testing comes integration testing, which makes sure that all of those individual units you have been
building fit together properly to make a complete application. For example, suppose an application that you are
writing needs to consult a local web service to obtain configuration data, including the name of a relevant database
3.6 Understanding Data Formats  host. You might want to test the values of variables set when these functions are called. If you were using PyTest,
you could do that like this:
Software Development and
3.7
Design Summary 
import requests # python module that simplifies making web requests
def get_config():
Understanding and Using return requests.get("http://localhost/get_config").content
4  def set_config(dbhost):
APIs
requests.get("http://localhost/config_action?dbhost="+dbhost)
save_dbhost = ""
5 def setUp():
Network Fundamentals 
global save_dbhost
save_dbhost = get_config()
Application Deployment and def tearDown():
6  global save_dbhost
Security
set_config(save_dbhost)
def test_setconfig():
Infrastructure and setUp()
7 
Automation set_config("TESTVAL")
assert get_config() == "ESTVAL"
Cisco Platforms and tearDown()
8 
Development

https://contenthub.netacad.com/devnet/3.5.1 5/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing
Note that your test_setconfig() method deliberately calls your setUp() function before running tests, and your
tearDown() function afterward. In unittest, methods called setUp() and tearDown() are provided by the
TestCase class, can be overridden in your defined subclass, and are executed automatically.
3.3.9 Branching Features
Show Menu Running this code with PyTest might produce output like this:

3.3.10 .diff Files Development and


Software
3  ============================== test session starts ===============================
Design
Lab - Software Version Control platform linux2 -- Python 2.7.15+, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
3.3.11
with Git rootdir: /home/ubuntu/deploysample, inifile:
collected 1 item
test_sample_app.py F [100%]
3.4 Coding Basics  ==================================== FAILURES ====================================
_________________________________ test_setconfig _________________________________
Methods, Functions, Modules, and def test_setconfig():
3.4.1
Classes setUp()
set_config("TESTVAL")
3.4.2 Clean Code > assert get_config() == "ESTVAL"
E AssertionError: assert 'TESTVAL' == 'ESTVAL'
E - TESTVAL
3.4.3 Methods and Functions
E ? -
E + ESTVAL
3.4.4 Modules test_sample_app.py:21: AssertionError
------------------------------- Captured log call --------------------------------
connectionpool.py 225 DEBUG Starting new HTTP connection (1): localhost:80
3.4.5 Classes
connectionpool.py 437 DEBUG http://localhost:80 "GET /get_config HTTP/1.1" 200 7
connectionpool.py 225 DEBUG Starting new HTTP connection (1): localhost:80
3.4.6 Lab - Explore Python Classes connectionpool.py 437 DEBUG http://localhost:80 "GET /config_action?
dbhost=TESTVAL HTTP/1.1" 200 30
connectionpool.py 225 DEBUG Starting new HTTP connection (1): localhost:80
3.5 Code Review and Testing 
connectionpool.py 437 DEBUG http://localhost:80 "GET /get_config HTTP/1.1" 200 7
============================ 1 failed in 0.09 seconds ============================
What is a Code Review and Why
3.5.1
Should You Do This?
If you fix the broken test, you can see that everything runs perfectly:
3.5.2 Types of Code Reviews
============================== test session starts ===============================
platform linux2 -- Python 2.7.15+, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
3.5.3 Testing
rootdir: /home/ubuntu/deploysample, inifile:
collected 1 item
3.5.4 Unit Testing test_sample_app.py . [100%]
============================ 1 passed in 0.07 seconds ============================
3.5.5 Integration Testing
Again, you should run your integration tests before you make any changes for the day, whenever you make
significant changes, and before you close out for the day. If you are using Continuous Integration, any errors you
3.5.6 Test-Driven Development (TDD)
find must be corrected before you do anything else.

3.5.7 Lab - Create a Python Unit Test Note: You can run this script on your VM using pytest. However, understanding the output and fixing any errors is
beyond the scope of this course.

3.6 Understanding Data Formats 

Software Development and


3.7
Design Summary 
3.5.6

Understanding and Using


Test-Driven Development (TDD) 
4 
APIs

Building small, simple unit and integration tests around small bits of code helps in two ways:
5 Network Fundamentals 
It ensures that units are fit for purpose. In other words, you make sure that units are doing what requirements
dictate, within the context of your evolving solution.
Application Deployment and It catches bugs locally and fixes them early, saving trouble later on when testing or using higher-order parts of
6 
Security your solution that depend on these components.

The first of these activities is as important as the second, because it lets testing validate system design or, failing
Infrastructure and
7  that, guide local refactoring, broader redesign, or renegotiation of requirements.
Automation

Testing to validate design intention in light of requirements implies that you should write testing code before you
Cisco Platforms and write application code . Having expressed requirements in your testing code, you can then write application code
8 
Development until it passes the tests you have created in the testing code.

https://contenthub.netacad.com/devnet/3.5.1 6/7
7/23/24, 8:59 AM DevNet Associate -Code Review and Testing
This is the principle of Test-Driven Development (sometimes called Test-First Development). The basic pattern of
TDD is a five-step, repeating process:

3.3.9 Branching Features 1. Create a new test (adding it to existing tests, if they already exist). The idea here is to capture some
Show Menu requirement of the unit of application code you want to produce.
2. Run tests to see if any fail for unexpected reasons. If this happens, correct the tests. Note that expected
3.3.10 .diff Files Development and
Software failures, here, are acceptable (for example, if your new test fails because the function it is designed to test does
3 
Design not yet exist, that is an acceptable failure at this point).
Lab - Software Version Control 3. Write application code to pass the new test. The rule here is to add nothing more to the application besides
3.3.11
with Git what is required to pass the test.
4. Run tests to see if any fail. If they do, correct the application code and try again.
3.4 Coding Basics  5. Refactor and improve application code. Each time you do, re-run the tests and correct application code if you
encounter any failures.
Methods, Functions, Modules, and
3.4.1 By proceeding this way, the test harness leads and grows in lockstep with your application. This may be on a line-
Classes
by-line basis, providing very high test coverage and high assurance that both the test harness and the application
are correct at any given stopping-point. Co-evolving test and application code this way:
3.4.2 Clean Code

Obliges developers to consistently think about requirements (and how to capture them in tests).
3.4.3 Methods and Functions Helps clarify and constrain what code needs to do (because it just has to pass tests), speeding development
and encouraging simplicity and good use of design patterns.
Mandates creation of highly-testable code. This is code that, for example, breaks operations down into pure
3.4.4 Modules
functions that can be tested in isolation, in any order, etc.

3.4.5 Classes

3.5.7
3.4.6 Lab - Explore Python Classes

Lab - Create a Python Unit Test 


3.5 Code Review and Testing 

What is a Code Review and Why In this lab, you will complete the following objectives:
3.5.1
Should You Do This?
Part 1: Launch the DEVASC VM
3.5.2 Types of Code Reviews Part 2: Explore Options in the unittest Framework
Part 3: Test a Python Function with unittest

3.5.3 Testing

 Create a Python Unit Test


3.5.4 Unit Testing

3.5.5 Integration Testing

 Coding Basics 
3.4 3.6
Understanding Data Formats
3.5.6 Test-Driven Development (TDD)

3.5.7 Lab - Create a Python Unit Test

3.6 Understanding Data Formats 

Software Development and


3.7
Design Summary 

Understanding and Using


4 
APIs

5 Network Fundamentals 

Application Deployment and


6 
Security

Infrastructure and
7 
Automation

Cisco Platforms and


8 
Development

https://contenthub.netacad.com/devnet/3.5.1 7/7

You might also like