DEVTEST: Device Test Framework¶
The devtest project is a device testing framework that is part of the Pycopia suite of projects. It is a system level testing framework, designed specifically for testing devices in labs or end-to-end environments.
Motivation¶
The primary motivation of devtest is to be the framework that can easily and reliably test a device that is embedded in a large, complex environment.
The design is driven by the following requirements.
The need for fast regression testing of the entire system.
Accurate, consistent, and trustworthy results. - A Pass indication means that the feature was tested and works as expected. - A Failed indication means that the feature under test does not meet expectations.
A need to test on multiple types of environments. - Tests should be portable across environments.
Need to test complex scenarios. - Need to assemble a complex testing environment that closely models real world usage.
Need to troubleshoot problems quickly. - Test frameworks should enable fast defect isolation.
Background¶
First, some refresher on testing and frameworks in general.
Types of Testing¶
Testing can be divided into different levels. Three major ones are…
Unit Level Testing
Sometimes called small tests.
Test the smallest testable unit of software, such as function or method.
Run in an isolated environment, typically with mocked inputs.
Integration Level Testing
Sometimes called medium level tests.
Tests that cover larger units of code that interconnect.
Tests for matching communication protocols, data flow, interactions, etc.
May use real dependencies, such as a database.
System Level Testing
Sometimes called large tests.
Tests overall functional requirements.
May treat the device under test (DUT) as a black box.
Measure other characteristics, such as performance, power consumption.
May stress the system.
Test Case Characteristics¶
The different types of testing can require different types of test cases.
Unit Tests¶
Typical traits of a unit test are:
They are stateless and may be run in any order.
They run in an isolated environment that is more reliable.
They require only a single host to run on.
They are typically written in the same language as the software unit under test.
Integration Tests¶
Typical integration test characteristics.
These tests often require some external resource to be set up before it can run.
The resource is usually lightweight and also runs on the same host as the test.
A unit test framework is often used for integration testing as well.
System Tests¶
System level testing, also called end-to-end testing, can have very different requirements as compared to unit testing. A system level test case has the following characteristics.
They may alter the state of the device under test (configuration).
They may depend on the previous test completing successfully.
They may need to run in a specific order.
They often run in complex environments that may fail in other ways.
They may have to utilize other, external equipment.
They may need to measure and record device characteristics.
They may require human input in some cases.
Testing Frameworks¶
People have written testing “frameworks”, or “harnesses” for these different kinds of testing.
Unit Test Frameworks¶
A software framework for testing small units of code are called Unit Test Frameworks. Most frameworks are of this type.
One of the ancestors of this type of framework is SUnit, for the Smalltalk language. It is an object-oriented framework. It uses classes to contain a set of cases as methods. Subsequent unit tests frameworks copied its design. Framework such as JUnit, NUnit, and unittest are of this type. The general pattern is often call xUnit test frameworks.
Integration Test Frameworks¶
Most often a unit test framework is also used for integration tests.
System Test Frameworks¶
In spite of the test type differences described above, many people try to adapt a unit test framework for system level testing. This is not a good fit, and often results in slower pace of test development. A framework specifically designed for system level testing is needed.
Modern system level test frameworks tend to focus on the Web ecosystem, for both front-end and back-end. Some examples are:
Robot Framework
Appium
Cucumber
This framework is called devtest, and it is a system level test framework that primarily targets devices that may not be web applications. Examples would be hand-held devices (phones), devices that you may find in a closet or data center (routers, switches), or others that may or may not have a user interface.
Even so, it may also be used for testing web applications, back-ends, front-ends, and any other kind of system. It may also test applications that run on other devices.
Devtest Framework Implementation¶
The devtest framework is an open-source framework that provides, among others, the following features.
Full-cycle test case management.
Rapid test development.
Complete test bed modeling and equipment management.
Better differentiation between failed tests and failed infrastructure.
Dynamic selection of test cases.
Robust troubleshooting aids.
Flexible reporting.
Concurrent services.
General purpose modules for developing device controllers.
Protocol modules
Device interfaces
process manager
Etc.
Programming Language¶
The devtest framework is written in the Python programming language. The test cases are written in Python.
Python is a modern, dynamic, object-oriented scripting language.
It has good exception handling and error reporting.
Large collection of third-party packages that may be utilized.
Relatively easy to get started with, and contribute test cases.
Leverages Python exception handling to simplify test case code…
Low-level device controllers may raise exceptions when anything goes wrong.
High level runner catches exceptions and reports them. It may also abort.
Test case code is in the middle. You may write code optimistically while not missing error conditions.
Bail out early on errors; don’t continue if it doesn’t make sense.
Leverage Python packaging…
Hierarchical package structure to better organize test cases.
A package namespace, named testcases, is defined for all test cases to reside in.
Distribute different sets of test cases independently.
Leverage Python introspection…
Uses introspection to find and report on available test cases.
Other tools may load and inspect test case documentation and code without actually running it.
Export test plans to Wiki pages, web servers, or databases.
Find implemented test cases easily.
Major Framework Features¶
Intended to support and streamline the entire range of testing activities…
Managed test cases.
Abstract test bed and equipment model.
A means to select and run test cases in flexible ways.
A means to report accurate test case results, and persist them.
Run from anywhere, by anyone, including non-persons (CI).
Support data collection and analysis.
Support Manual Testing…
Supports manual testing procedures in a uniform way.
Mix together automated and manual tests in the same suite.
Allows for human input for tests that require it.
Scenario Based Testing¶
Influenced by the testing paradigm called “Scenario Based Testing.”
Test cases are grouped into suites when they run.
Suites are build by Scenario objects. These define the test scenario. You can have many of these that re-use test cases in various combinations.
Test suites are…
Dynamic, allowing for run-time selection of tests to be placed in the suite.
Or static, for consistent scenario runs.
They may be nested. Run a test suite inside another test suite, to any depth.
Managed Test Cases¶
Test case implementations are not just a loose collection of scripts. They are…
Documented Python modules that are importable and inspectable.
Organized into a logical structure using sub-packages.
Searchable without running them.
Versioned to match the current feature set of the device under test.
The test case implementation is never run directly. They are always invoked by the test runner.
Quality Test Case Code¶
Facilitate writing quality test cases.
Test cases should be easy to write, understand and maintain.
Enable contributions from part-time implementer.
Support rapid development: built-in debugging, good diagnostics, meaningful errors.
Have accurate, trustworthy results.
No false positives, or false negatives. PASSED means passed, FAILED means failure.
Abstract run-time environment¶
Generalize the test case code by writing to abstract device APIs. Use only attribute names, never device specific information in your code.
Use the testbed object to obtain test bed information.
Use equipment attributes, instead of hard-coded values.
Use the ip_address attribute, NOT 10.10.1.100.
Use the user or login attribute and credentials, NOT hard-coded credentials.
This makes test cases…
Portable across testbeds.
Compose-able, reusable in different scenarios.
Abstract Equipment Model¶
The framework has a database that models equipment and their relationships.
Important attributes for each equipment, such as model name, serial number, unit name, location, and interfaces.
Network connections and addresses.
Various device interconnections (USB, power).
Testing fixture attributes.
Account information for logging in.
Any other information you might want to add.
Test Structure¶
The structure of test cases are based on Python packages, modules, and classes…
Using Python package hierarchy, with modules.
Small, single-purpose test case, implemented as a subclass of TestCase.
Declarative as much as possible.
Decoupled. No direct calling to other test case methods. Dependencies are declared.
Managed in a SCM, like git. Versioned and branched to match product.
Test plan prose is also kept inside the test case module itself. Use the source…
It is the primary test case documentation.
As it is the source of truth for test case details.
The source is more likely to be kept up to date.
Tools extract and publish this prose to wider audiences.
Consistent document structure.
Manual tests also benefit from it, treating them consistently with automated test.
Consequently, the framework defines a canonical test name as the full package path ending with the TestCase subclass.
Examples…
testcases.dut.disk.DiskSpaceChecks
testcases.dut.system.CheckSystemErrors
testcases.dut.camera.CameraChecks
This is analogous to a file system path. The path part being packages and module, and the TestCase class being the file.
Framework’s testing object model.
![digraph {
rankdir=LR;
labelfontname = "Roboto";
node [fontname="Roboto", fontsize=18, shape=rect, style=rounded];
edge [fontname="Roboto", fontsize=12];
"TestResults" [shape="cylinder"];
"TestCase" [shape="box3d"];
"Scenario" -> "TestSuite" [label="creates", style=dashed];
"TestSuite" -> "TestCase" [label="contains"];
subgraph cluster_results {
style = "dashed";
pack = true;
"TestCase" -> "TestResults" [label="produces"];
}
}](_images/graphviz-3e2f571cf3904401066a89d5590468d0839c8f63.png)
Test cases (
TestCaseobject) implement tests. One subclass per test case.Test suites (
TestSuiteobject) contains a sequence of TestCases and runs them in the order added.Scenarios (
Scenarioobject) construct suites at run time.They may inspect the runtime configuration and make adjustments to the suite at that time.
They may just hard-code a set of test cases.
A
TestSuiteis polymorphic with a test case, and may be nested, creating a tree structure.
A test case class may have any name you choose. There is no requirement for it to contain a substring of “Test”, or test_ or any other variant.
Test Outcomes¶
Since system tests incorporate many intermediate paths or components there are many more possibilities of failure.
Infrastructure |
Product |
|---|---|
Works |
Pass |
Works |
Fail |
Error |
Unknown |
The framework should not report a product failure if the test itself, the software framework, or the harness, failed. In such cases the outcome of the DUT feature test is unknown. This frameworks labels that outcome as incomplete.
Possible Test Results¶
There are several possible test results…
PASSED: The test passed (pass criteria was met). A test case should positively determine this, with explicit notification.
FAILED: The test failed (criteria was not met), but the suite can continue. This must be explicitly indicated in the code.
INCOMPLETE: The test could not complete, so the pass/fail criteria could not be determined. This may happen when the test itself fails, for any reason. A test may also indicate this explicitly.
EXPECTED_FAIL: The test is failing due to a known bug, so it is already known to fail. New runs shouldn’t report as a new failure.
ABORTED: test could not complete, and the suite cannot continue. Used when test run is interrupted.
Runner¶
A test runner handles the setup and teardown of the test bed and data model. The devtester command line tool is the main entry point for running test cases.
It manages all framework initialization and teardown.
Sets up requested report types.
Prepares service modules.
Reports an error code to shell, based on summarized test result.
Example:
devtester --testbed=system1 testcases.system.SystemUpdateScenario
The test runner allows you to…
Search for and run the “runnable object” provided on the command line.
Run ad-hoc tests suites without having to edit any code or configuration files.
Provide options to any parameterized tests.
Select the target test bed.
Select the output destination (run-time report).
Set other options such as debug feature and output verbosity.
Controllers¶
Most tests will interface to one or more devices through a controller, or device object. These are obtained through the testbed and equipment objects that are injected into every test case.
Abstract interface to a class of similar devices.
Performs operations on remote equipment, and the system under test.
A controller implements a function, sometimes called the role.
The role uses an equipment to implement the functionality.
Multiple equipment objects can provide the same role.
A single equipment may provide multiple roles.
Reports¶
The framework has a modular, and extensible result reporting system.
Report objects produce the outputs of test runs. They can…
write to console
Write a persistent file, such as HTML files.
Save to result records in a database.
Notify slack channels.
… whatever else is required.
Configuration¶
The framework has a YAML format configuration file. Any information can be placed there and obtained through the config object in a test case. Options given on the command line can override any entry found there.
Service Architecture¶
Some tests may require a general service that needs to run concurrently with the test. The framework has a modular, and extensible service provider system.
Examples include…
Capturing console output during a test run.
Capture a video stream.
Record logging streams.
Start power consumption measurement.
A service…
provides a concurrent, run-time service for test cases.
uses a broadcast-response (signal) API that decouples test code from the service.
is started when requested.
may be requested for a device by a test case.
Testbeds¶
A Testbed is a collection of equipment and assigned roles. It has…
All the facts about all testbeds and equipment.
Interconnections
Network interfaces
Account credentials for accessing devices that need one.
Assigns roles for each equipment.
Any arbitrary attributes you want to add.

Item |
Description |
|---|---|
EquipmentModel |
The type of equipment and its attributes (such as part no.) |
Equipment |
A specific equipment and its attributes (such as serial no.) |
Function |
The function, or role. |
TestEquipment |
A combination of Equipment and Function. |
Testbed |
The collection of TestEquipment. |
Implementation |
path to Python object that implements the role. |
EquipmentModel¶
Not to be confused with THE equipment model. This is a type of equipment. Contains attributes that are common to all instances of this type. Such as:
Manufacturer
Part number or name
Common capabilities or attributes
Equipment¶
A specific EquipmentModel. It has attributes specific to one equipment. Such as:
A unique name.
The unique serial number.
Any network interfaces and addresses.
Connections to other devices.
Physical location.
Function¶
A function, also known as the role, specifies what the equipment does.
Description of what it does.
Links to an actual implementation in the framework’s code base.
An Equipment may have multiple roles, in which has it’s added multiple times to the test bed with a different role.
Testbed¶
Contains any equipment and also defines equipment roles in the test bed.
The primary entity that test runs target.
Contains the system under test.
May contain user defined attributes.
Test Case Storage¶
Besides the code base, a database also holds information about test cases. They are synchronized with code base. These are referenced by test results when results are recorded to the database.
You can search for test cases by name or keyword.
View the documentation from alternate user interfaces.
Has a collection of TestResults associated with it.
Test Results¶
When a test is run with the report named database for output, it will write result records to the database.
Test suites also aggregate test case results.
Test runs aggregate suite results.
Thus a complete result record is a tree structure matching the run’s suite and test structure.
You may also attach arbitrary data to a test result.
Test cases as data acquisition.
Analyzer objects may then be written to extract and report on it.
Test Case Details¶
How are test cases written? They are the documentation strings of the Python test case class.
The test case prose is treated like code. You can the leverage code work flows.
Features of developer workflow tools, such as peer reviews.
Test case prose that is versioned along with the implementation.
May be branched along with the product code, keeping functionality aligned.
Manual Testing¶
Manual tests may also be contained in the automation framework. Why?…
Same review process.
Increase the efficiency of manual testing:
Leverage automation for setup phase.
Automatic recording of outcome to the same reporting system.
Automatic use of service modules.
Procedure is performed consistently.
Test may use equipment data as memory aids and prompts.
Deploying¶
Test cases are published as Python packages.
Different user groups may produce their own sets of tests.
Packages of tests have their own dependencies.
Installed with standard package manager (pip).
They are joined together in a root “namespace package”, called testcases.
Test case packages may be…
built as an installable format called wheel files.
placed on shared package repositories, such as Artifactory.
have versions that may be selected by installer.
Can be easily installed where needed, such as CI systems.
Example Test Case¶
Here is the general structure of an automated test case looks like. Each test case is a subclass of the TestCase base class. That is what determines that it’s a test. It has a type of TestCase.
from devtest.qa import core
class MyTestCase(core.TestCase):
"""
Purpose
-------
Documentation, test plan is contained in the code.
...
"""
def procedure(self):
result = do_something_here()
if result:
self.passed("The test meets the criteria")
else:
self.failed("The test did NOT meets the criteria")
Test Case Document Sections¶
Test case details are contained in the class documentation. Note that the documentation is interpreted as ReStructuredText by other tools.
Several sections are pre-defined and should be filled out.
Purpose
Pass Criteria
Start Condition
End Condition
Reference
Procedure
Purpose Section¶
Documents the purpose of the test case. What is it testing?
"""
Purpose
-------
The purpose of this test case.
...
"""
Should be a paragraph or two.
Pass Criteria Section¶
Describe in more detail what it means to pass this test.
"""
...
Pass Criteria
-------------
What is the pass criteria?
...
"""
Start Condition Section¶
System test cases depend on the system under test being in a particular state to start. Describe that condition that has to exist before the test can run successfully.
"""
...
Start Condition
---------------
What is the state of the DUT this test needs?
...
"""
This relates to the prerequisites.
End Condition Section¶
System test cases may alter the state of the system under test as a side effect. Document what the effect is here. Then you can chain sequences of actions as individual test cases.
"""
...
End Condition
-------------
What changes to the condition or state of the DUT are made?
...
"""
Reference Section¶
A test case is usually written to test some documented feature of the system. Reference the source document, usually some specification or plan, and the section here.
"""
...
Reference
---------
Reference to design document or specification clause, or a URI.
...
"""
Procedure Section¶
A step-by-step procedure of the test case. Ideally, this would be written in a way that a person could follow to perform the test manually. Another person should be able to tell what the test does without reading the implementation code.
"""
...
Procedure
---------
#. Step 1 ...
#. Step 2 ...
#. Step 3 ...
"""
Test Class Attributes¶
Since all test cases are one class you can specify test metadata as class attributes. You may also add test-specific constants for the code here.
Some class attributes have special meaning.
- PREREQUISITES
A list of test cases that must pass in order for this test to start.
This allows test cases to be skipped if the prerequisite is not met.
Code¶
This is where your executable test logic goes. There must always be the procedure method. It may take arguments.
This is where you access the objects injected by the runner, such as testbed, and config.
def procedure(self):
dut = self.testbed.get_role("dut")
if tested_something_is_good(dut):
return self.passed("Pass Criteria was met.")
else:
return self.failed("Pass Criteria was NOT met.")
Note the explicit use of passed or failed methods. This is the only way these outcomes are reported. The framework also enforced outcome integrity by checking for conflicting indications.
Create Your Own Test Case¶
The framework leverages Python package hierarchy to organize test cases. You can decide how that is organized. One example would be by functional area.
There is a template module inside testcases named _template.py that you can start from.
First, decide on a good category for the test case.
Copy the template file to the new module name in the appropriate place. For example, for a new DUT test module:
cp testcases/_template.py testcases/system/update.py
Then edit the new file, replacing occurrences of the substring XXX to something meaningful. Follow the directions in the template.
- If you name the TestCase subclass something like PerformUpdate, for example, you would then
address it as testcases.system.update.PerformUpdate to the runner and documentation.
Then add, commit, and review just like other code.
Finding and Running¶
The test runner tool, devtester may show you the available test case implementations by using the -l option.
$ devtester -l
Runnable objects:
test testcases.examples.demo.BasicReadinessCheck
scenario testcases.examples.demo.DemoScenario
test testcases.examples.demo.ErrorCheck
test testcases.examples.demo.FailCheck
test testcases.examples.demo.PassCheck
scenario testcases.examples.demo.PassFailErrorScenario
test testcases.examples.demo.WithData
test testcases.examples.eat.EatTheApple
scenario testcases.examples.eat.EatingScenario
test testcases.examples.interactive.InteractiveTest
test testcases.examples.remotecode.RemoteCode
test testcases.system.update.PerformUpdate
Then run your new test.
devtester -d --testbed=default testcases.system.SystemUpdateScenario
The -d flag enables debug mode, useful for new case case code.
The demo test PassCheck can be run like this.
devtester testcases.examples.demo.PassCheck
Which results in.
╔══════════════════════════════════════════════════════════════════════════════╗
║ Start run at 20:07:21.221691 ║
╚══════════════════════════════════════════════════════════════════════════════╝
Results location: /home/keith/tmp/resultsdir/20261025_030721
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Start TestSuite: PassCheckSuite 20:07:21.339611┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
examples.demo.PassCheck 20:07:21.339722
Arguments:
✔ Always passes
examples.demo.PassCheck ended at 20:07:21.339858 elapsed: 0:00:00.000136
TestSuite 'PassCheckSuite' ended at 20:07:21.339903
Aggregate Suite Result: PASSED(0)
Runner end at 20:07:21.340024.
This is the default report output.
API Documentation¶
For more information please refer to the built in documentation.