checkbox-ng-0.23/0000775000175000017500000000000012633675304014437 5ustar pierrepierre00000000000000checkbox-ng-0.23/docs/0000775000175000017500000000000012633675304015367 5ustar pierrepierre00000000000000checkbox-ng-0.23/docs/scripts/0000775000175000017500000000000012633675304017056 5ustar pierrepierre00000000000000checkbox-ng-0.23/docs/scripts/index.rst0000664000175000017500000000021712627266441020720 0ustar pierrepierre00000000000000Test Scripts ============ Test 'scripts' are small programs which are used to aid in implementing tests. .. toctree:: brightness_test.rst checkbox-ng-0.23/docs/scripts/brightness_test.rst0000664000175000017500000000105112627266441023015 0ustar pierrepierre00000000000000brightness_test =============== This script tests the brightness of the systems backlight can be changed by using the kernel interfaces in /sys/class/backlight. There may be more than one interface to choose from, so the correct interface to use is selected by using the heuristic prescribed in https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-backlight. The brightness is manipulated by updating the brightness file of the interface and the actual_brightness file is checked to see if the value was modified to the brightness selected. checkbox-ng-0.23/docs/bugs.rst0000664000175000017500000000163112627266441017063 0ustar pierrepierre00000000000000Reporting Bugs ============== To report bugs on the Checkbox project you will need a launchpad account. You may find `instructions on how to create one `_ useful. Once you have an account you can `report bugs `_. On that page you can select the project you wish to file the bug on (we use a number of projects to coordinate releases and we prefer to have bugs associated with appropriate part of Checkbox). If you know the right project to use, just use it and file the bug. If you don't know Checkbox internals that much or are in doubt just file it on the base 'Checkbox' project (you can use `this direct link `_.) A member of the development team will review your bug and re-assign it to the appropriate location. The bug number will not change when that happens. checkbox-ng-0.23/docs/index.rst0000664000175000017500000000355512627266441017241 0ustar pierrepierre00000000000000.. CheckboxNG documentation master file, created by sphinx-quickstart on Wed Feb 13 11:18:39 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. CheckboxNG ========== CheckboxNG is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`Checkbox` that is built directly on top of :term:`PlainBox` CheckboxNG *replaces* Checkbox, where applicable. .. warning:: Documentation is under development. Some things are wrong, inaccurate or describe development goals rather than current state. Installation ^^^^^^^^^^^^ CheckboxNG can be installed from a :abbr:`PPA (Personal Package Archive)` (recommended) or :abbr:`pypi (python package index)` on Ubuntu Precise (12.04) or newer. .. code-block:: bash $ sudo add-apt-repository ppa:checkbox-dev/ppa && sudo apt-get update && sudo apt-get install checkbox-ng Running stable release update tests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ CheckboxNG has special support for running stable release updates tests in an automated manner. This runs all the jobs from the *sru.whitelist* and sends the results to the certification website. To run SRU tests you will need to know the so-called :term:`Secure ID` of the device you are testing. Once you know that all you need to do is run: .. code-block:: bash $ checkbox sru $secure_id submission.xml The second argument, submission.xml, is a name of the fallback file that is only created when sending the data to the certification website fails to work for any reason. Table of contents ================= .. toctree:: :maxdepth: 2 bugs.rst stack.rst changelog.rst scripts/index.rst profiles.rst launcher-tutorial.rst release.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` checkbox-ng-0.23/docs/profiles.rst0000664000175000017500000001153312627266441017750 0ustar pierrepierre00000000000000Profiles configuration ^^^^^^^^^^^^^^^^^^^^^^ Execution profiles, or launchers, allow specifying a predefined set of configuration options that allow customization of the welcome screen, displayed whitelists as well as saving results locally or sending the submission file to Launchpad or to the Certification database/HEXR, as well as some other parameters. The profile settings are part of a launcher script and use either checkbox-gui or checkbox-launcher (in text-mode/CLI) as a shebang to interpret the key/values. This document provides a reference on launcher functionality and syntax. To understand the design and concepts and see several examples, you may want to read the :doc:`tutorial` on how to create launchers and their relationship with legacy :term:`Checkbox`. Syntax ====== As checkbox-gui is a Qt application, settings must follow the INI-style rules of the `QSettings `_ class. Multiple-line values are supported but must be enclosed in doubles quotes and extra lines must start with one space, e.g: .. code-block:: bash [category] key = "Hello World" - From QML: .. code-block:: bash settings.value("category/key", i18n.tr("default_value")) - From C++: .. code-block:: bash settings->value("category/key", app.tr("default_value")) Conversely, checkbox-launcher-specific launchers must follow `Python ConfigParser `_ syntax. Also, some settings only make sense for either GUI or CLI, and are thus not understood by the other. These are noted below. Supported Settings ================== welcome/title QML application title and welcome screen header. Defaults to ``System Testing``. welcome/text Welcome message to display on the first screen (checkbox-gui supports Rich text allowing HTML-style markup). Defaults to ``

Welcome to System Testing.

[...]`` suite/whitelist_filter Regular expression to match a subset of whitelist filenames. On checkbox-gui it defaults to ``.*``. For checkbox-launcher it has no default and *must* be defined. suite/whitelist_selection Pattern that whitelists need to match to be preselected. Python regular expression. It has no default and *must* be defined. (CLI only) suite/skip_whitelist_selection If set to true, user will not receive a choice of whitelist. Only the preselected ones (see whitelist_selection) will be selected. (CLI only). suite/skip_test_selection If set to true, user will not be allowed to deselect tests prior to run: all tests in the selected whitelist will be run. (CLI only) submission/message Header text of the submission pop-up , shown to the user after submission has completed. (GUI only) submission/input_type Show a Text input field to enter the secure ID or the LP address (default). To just save the results to disk, must use the ``none`` value. To validate using a regex, must be ``regex``. (GUI only) submission/regex Regular expression to validate input in submission field (e.g. email, secure_id) if input_type is regex. (GUI only). RegExpValidator, default ``.*`` submission/input_placeholder Temporary text to put in input field, used to guide the user. ``Launchpad E-Mail Address`` (default) or ``Secure ID (15 or 18 characters)``. (GUI only) submission/secure_id Preconfigured secure_id to fill in the text field. submission/ok_btn_text The label for the "Send" button. ``Submit Results`` (default) or ``Save Results``. (GUI only) submission/cancel_warning Show to the user if he wants to exit without having saved the report. You are about to exit this test run without saving your results report. Do you want to save the report? (GUI only) submission/submit_to_hexr Boolean, add an extra header to also send the results to HEXR (works with the certification transport) exporter/xml_export_path Location to save the XML submission file, if set to an empty string will open a file save dialog. Default: ``/tmp/submission.xml`` (GUI only) transport/submit_to Transport endpoint. Defaults to ````. Supports submission to LP (the default, value ``launchpad``), ``certification``, or ``local`` (save to disk) transport/submit_url URL to submit results to. This allows to upload to different websites, for example it can upload directly to hexr, or to the staging sites. Used only with the ``certification`` submit_to value. transport/config_filename Name of a custom config file to load. Config files are mainly used to define environment variables. (CLI only) transport/dont_suppress_output If set, resources, local jobs and attachments will be output to screen, this generates a lot of text and is mainly for debugging. (CLI only) checkbox-ng-0.23/docs/stack.rst0000664000175000017500000002152012627266441017227 0ustar pierrepierre00000000000000The "Checkbox Stack" ==================== The Checkbox Stack is a collection of projects that together constitute a complete testing and certification solution. It is composed of the following parts (see table below for extra details). All of the projects are linked to from the `Launchpad project group `_. Architecture Diagram -------------------- .. image:: _images/Checkbox-Stack-Architecture.svg :alt: Architecture Diagram This diagram contains a high-level approximation of the current Checkbox architecture. There are three main "pillars". On the left we have *end products*. Those are actual tools that certification and engineers are using. On the right we have the *test market*. This is a open market of tests vendors and suppliers. The tests are wrapped in containers known as providers. In the center we have three shared components. Those implement the bulk of the framework and user interfaces for test execution. Finally in the bottom-left corner there is a part of checkbox (a library) that is shared with HEXR for certain tasks. HEXR is a out-of-scope web application used by part of the certification process. Arrows imply communication with the shape of the arrow shows who calls who. As mentioned before, in the center column there are three main components of shared code (shared by everyone using the end products that are discussed below). The shared code is composed of plainbox, checkbox-ng and checkbox-gui. Component responsibilities are discussed in more detail in the table below. Here we can see that checkbox-gui used DBus API exposed by checkbox-ng, which in turn uses checkbox-support (a helper library separated out so share some code with HEXR) and plainbox. In the right hand side column there are various test providers. The checkbox project is producing and maintaining a number of providers (see the table below) but it is expected that our downstream users will also produce their own providers (specific to a customer or project). Eventually some providers may come from third parties that will adopt the format. Lastly in the bottom-left corner, the shared library, this library contains many parsers of various file formats and output formats. Technically this library is a dependency of HEXR, checkbox-ng *and* of providers. As an added complexity the library needs to be called from python3 code and python2 code. .. note:: The communication between checkbox-ng and plainbox is bi-directional. Plainbox offers some base interfaces and extension points. Those are all exposed through plainbox (using common APIs) but some of those are actually implemented in checkbox-ng. .. warning:: All internal APIs are semi-unstable. The DBus API is more stable in practice but should not be relied upon. Projects are encouraged to be merged into lp:checkbox where API transitions can be handled gracefully. The only stable API is are file format specification (job definitions and whitelits). Launcher specification will be stabilized in the next release. Component Descriptions ---------------------- +------------------------+---------------------------------------+-------------+ | Project | Responsible for | Type | +========================+=======================================+=============+ | Next Generation | - The C++/QML user interface | Application | | Checkbox (GUI) | - The graphical launcher for | | | | providers, e.g. | | | | checkbox-certification-client | | +------------------------+---------------------------------------+-------------+ | Next Generation | - The python command-line interface | Application | | Checkbox (CLI) | | | | | - the text user interface | | | | - the SRU testing command | | | | | | | | - Additional certification APIs | | | | | | | | - sending data to Launchpad | | | | - sending data to HEXR | | | | | | | | - the DBus service needed by GUI | | +------------------------+---------------------------------------+-------------+ | Client Certification | - canonical-certification-client | Provider | | Provider | executable | | | | - client certification whitelists | | +------------------------+---------------------------------------+-------------+ | Server Certification | - server certification whitelists | Provider | | Provider | - additional server whitelists | | +------------------------+---------------------------------------+-------------+ | System-on-Chip Server | - SoC server certification whitelists | Provider | | Certification Provider | | | +------------------------+---------------------------------------+-------------+ | Checkbox Provider | - Almost all job definitions | Provider | | | - Most of custom "scripts" | | | | - Default and SRU whitelist | | +------------------------+---------------------------------------+-------------+ | Resource Provider | - Almost all resource jobs | Provider | | | - Almost all resource "scripts" | | +------------------------+---------------------------------------+-------------+ | Checkbox Support | - Support code for various providers | Library | | | - Parsers for many text formats | | +------------------------+---------------------------------------+-------------+ | PlainBox | - Almost all core logic | Library | | | | and | | | - RFC822 (job definition) parser | Development | | | - Configuration handling | Toolkit | | | - Testing session (suspend/resume) | | | | - Job runner | | | | - Trusted launcher | | | | - Dependency resolver | | | | - Command line handling | | | | - The XML, HTML and XSLX exporters | | | | - and more... | | | | | | | | - Provider development toolkit | | | | | | | | - 'plainbox startprovider' | | | | - 'manage.py' implementation | | +------------------------+---------------------------------------+-------------+ | Legacy Checkbox | - Applications | Monolithic | | (no longer maintained) | | Application | | | - Qt4 GUI | Library | | | - Gtk2 GUI | and Data | | | - Urwid (text) GUI | | | | | | | | - Core | | | | | | | | - Plugin and Event / Message Engine | | | | - Almost Every feature implemented | | | | a core plugin | | | | | | | | - Data | | | | | | | | - Jobs and whitelists | | +------------------------+---------------------------------------+-------------+ checkbox-ng-0.23/docs/changelog.rst0000664000175000017500000000142212627266441020050 0ustar pierrepierre00000000000000ChangeLog ========= .. note:: This changelog contains only a summary of changes. For a more accurate accounting of development history please inspect the source history directly. .. _version_0_23: CheckboxNG 0.23 (unreleased) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Bugfixes: https://launchpad.net/checkbox-ng/+milestone/0.23 .. _version_0_22: CheckboxNG 0.22 ^^^^^^^^^^^^^^^ * Bugfixes: https://launchpad.net/checkbox-ng/+milestone/0.22 CheckboxNG 0.3 ^^^^^^^^^^^^^^ * Bugfixes: https://launchpad.net/checkbox-ng/+milestone/0.3 CheckboxNG 0.2 ^^^^^^^^^^^^^^ * Bugfixes: https://launchpad.net/checkbox-ng/+milestone/0.2 CheckboxNG 0.1 ^^^^^^^^^^^^^^ * Initial release * Support for displaying configuration * Support for running SRU tests (automatic regression testing) checkbox-ng-0.23/docs/release.rst0000664000175000017500000002211612627266441017544 0ustar pierrepierre00000000000000======================== Checkbox Release Process ======================== This page describes the necessary steps for releasing versions of Checkbox and Checkbox Certification to the stable PPA belonging to the Hardware Certification team, on a regular basis. Throughout this document the term 'Checkbox' is used as a catch-all term to cover all versions of Checkbox owned by the Hardware Certification team, currently Checkbox itself and the Checkbox Certification extensions. Overview ======== Currently the process runs on a bi-weekly cadence, with a new release of Checkbox every two weeks. This covers ten working days, and the tasks carried out on each day or group of days is described below: * Days 1-4: Time allowed for new changes to be introduced into trunk. * Day 5: Changes are merged from the trunk of ``lp:checkbox`` and ``lp:checkbox-certification`` to their respective release branches. The changelogs for both are *bumped* at this point and revisions are tagged. At this stage it may also be necessary to copy the package 'fwts' from the `FWTS Stable PPA `_ to the `Checkbox Release Testing PPA `_. * Days 6-9: Testing is performed by the release manager for the Hardware Certification team, and a representative of the CE QA team (the main customer for Checkbox within Canonical) * Day 9: A release meeting is held between the release manager for the Hardware Certification team and the representative of the CE QA team. Potential issues with the release are identified and plans made to address them. * Day 10: The tested version of Checkbox is copied to the stable PPA. Launchpad Branches ================== The release process requires separate branches in Launchpad containing a semi-frozen version of the code that was in trunk on day 5 of the process. This is so that development can continue on trunk without jeopardising the stability of the to-be released version of Checkbox. The relationship between all branches involved in the process is as shown below: * `lp:checkbox/release` <- `lp:checkbox` * `lp:checkbox-certification/release` <- `lp:checkbox-certification` * `lp:~checkbox-dev/checkbox/checkbox-packaging-release` <- `lp:~checkbox-dev/checkbox/checkbox-packaging` Auditing milestoned bugs ======================== Prior to creating the release candidate the release manager should review the list of bugs milestoned for the next release of Checkbox. They should visit `checkbox milestones `_ and locate the milestone dated with the release date. * For bugs that are set to In Progress with a branch associated - liase with the branch owner to see if the merge can be completed before the deadline. * For bugs that are in any other non-closed status (except *Fix Commited*) - re-milestone them to the following milestone. Cutting the release =================== In order to cut the release, we have to merge the changes from trunk into the release branch, commit them with a suitable message and update the changelog in trunk so that future changes go under the correct version. For each combination of branches shown above, do the following (the example uses ``lp:checkbox`` and ``lp:checkbox/release``):: bzr branch lp:checkbox/release checkbox-release bzr branch lp:checkbox checkbox-trunk cd checkbox-release current_stable=`head -n1 $(find . -name 'changelog') | grep -oP '(?<=\().*(?=\))'` bzr merge lp:checkbox at this point if no changes (other than one to ``debian/changelog``) get merged in then we do not perform a release of the package in question. In practice this often happens with ``checkbox-certification`` but never with ``checkbox``:: bzr commit -m "Merged in changes from rev$(bzr revno -r tag:$current_stable lp:checkbox) to rev$(bzr revno lp:checkbox) from lp:checkbox" bzr push lp:checkbox/release cd `find . -name 'debian'`; cd .. bzr tag `head -n1 debian/changelog | grep -oP '(?<=\().*(?=\))'` dch -r (save modified changelog) dch -i -U 'Incremented changelog' debcommit bzr push lp:checkbox The last step in the process is to perform a build of the packages in the ``ppa:checkbox-dev/testing PPA``. To do this we need to go to the recipe pages for the ``checkbox`` and/or ``checkbox-certification`` release branches. * `checkbox-testing recipe `_ * `checkbox-certification-testing recipe `_ The **Build Now** option should be available on the page. Click it to start a build. Copying Firmware Test Suite to the Testing PPA ============================================== The Firmware Test Suite tool is a test tool for system firmware that is naturally heavily utilised by Checkbox. To make sure the latest version which contains fixes and new tests/features needed by Checkbox is available and also doesn't break anything in Checkbox, we need to release it alongside Checkbox. After cutting the release if the Firmware Testing team have notified that a new version is available and that this version should be used for certification, we need to copy it to the Testing PPA. To do this we need to go to the `Copy packages view of the Firmware Test Suite (Stable) PPA `_ and select the 'fwts' packages for all releases back to Precise. We need to set the 'Destination PPA' as 'Checkbox Release Testing [~checkbox-dev/testing]' and the 'Copy options' field to 'Copy existing binaries', then click 'Copy packages'. This step then needs to be repeated but set the 'Destination PPA' field to 'PPA for Checkbox Developers [~checkbox-dev/ppa]'. Next Release of Checkbox e-mail =============================== So that everyone has the opportunity to perform whatever testing is required in a timely manner, after the PPA builds have been completed an email should be sent to the following mailing lists: * `hardware-certification-team@lists.canonical.com `_ * `commercial-engineering@lists.canonical.com `_ The content is typically something like this:: Subject: Next Release of Checkbox (18/11/2013) Hi, The next release of Checkbox is available in the https://code.launchpad.net/~checkbox-dev/+archive/testing PPA. Please test it at your convenience. Checkbox is based on revision 2484 of lp:checkbox and Checkbox Certification is based on revision 586 of lp:checkbox-certification. Thanks, If one or the other of Checkbox and Checkbox Certification have not been updated then there is no need to mention that package Testing the release =================== Now that the release has been cut, testing should take place prior to the release meeting. From the point of view of the certification team, what needs to be tested is ``checkbox-certification-client`` and ``checkbox-certification-server`` which form the basis for CE QAs OEM specific versions of Checkbox. Checkbox certification server is tested in the CI loop Checkbox certification client needs to be tested manually. Release Meeting =============== On the Thursday before the release is made, a meeting is held between a representative of the Certification team and a representative of the **Commercial Engineering QA** team. The meeting is held at 7:30 UTC as shown in this `calendar invite `_. An agenda for the meeting is included in the invite. Publishing the release ====================== To publish the release we simply need to copy a number of packages from the `Checkbox Release Testing PPA `_ to the `Hardware Certification Public PPA `_. To do this we go to the `Copy packages view of the Checkbox Release Testing PPA `_ and select all versions of the following list of packages: ``checkbox, checkbox-certification, fwts``. Make sure that the 'Destination PPA' field is set to 'Public PPA for Hardware Certification [~hardware-certification/public]' and that the 'Copy options' field is set to 'Copy existing binaries', then click 'Copy Packages'. After that is done an announcement email should be sent to `commercial-engineering@lists.canonical.com `_. A template for the announcement in included below:: Hi, A new release of checkbox has been uploaded to the Hardware Certification Public PPA (https://launchpad.net/~hardware-certification/+archive/public). The release is based on revision 2294 of lp:checkbox Thanks, Please attach the most recent part of the changelog as release notes checkbox-ng-0.23/docs/launcher-tutorial.rst0000664000175000017500000002736012627266441021574 0ustar pierrepierre00000000000000Checkbox/plainbox launchers tutorial ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This document provides an explanation of why launchers are necessary, what you can achieve with them, and goes over several examples to better describe their capabilities. For a detailed reference on which settings are supported by launchers, and specific syntax for launcher files, look at :doc:`/profiles`. Legacy checkbox behavior control ================================ In the past, :term:`Checkbox`'s behavior was controlled by three mechanisms. First, the functions of checkbox could be augmented by adding plugins. For example, the ability to submit to certification website was added by the checkbox-certification package using a plugin. The plugins included by checkbox-certification and which add new behavior to base checkbox were: :: /usr/share/checkbox-certification/plugins/certify_message.py /usr/share/checkbox-certification/plugins/submission_info.py /usr/share/checkbox-certification/plugins/backup.py /usr/share/checkbox-certification/plugins/certify_prompt.py /usr/share/checkbox-certification/plugins/certify_report.py /usr/share/checkbox-certification/plugins/certify_schemas.py These added the way to prompt the user for submission-specific data, generate the xml report, and other functions. Next, the behaviors of the plugins could be configured or controlled using configuration files, which are "cascaded". A config file can include others and those can in turn include others. This is an example of a project-specific project-qt.ini main config file. It's the first file read when the project-specific client is launched. Some settings are abbreviated: :: [DEFAULT] includes = %(checkbox_oem_share)s/configs/checkbox-project-base-qt.ini %(checkbox_project_share)s/configs/checkbox-project-base.ini [checkbox/plugins/environment_info] repositories = deb http://.*\(archive\|security\).ubuntu.com/ubuntu precise-security routers = multiple server_iperf = 10.20.30.40 sources_list = /etc/apt/sources.list wpa_n_psk = password wpa_n_ssid = access-point [checkbox/plugins/user_interface] title = My project System Testing Notice the includes line, this instructs it to load the config file for checkbox-project-base-qt and checkbox-project-base. Checkbox-project-base-qt loads the configs for checkbox-certification and checkbox-project. Settings are cascaded so the config options near the top override the ones near the bottom. Finally, the "binary" used to invoke checkbox is a shell script that defines where to find the things checkbox needs to run: you can define a share directory, a specific data directory, point to a configuration file and define some environment variables that you may need during testing. Here's an example for checkbox-project-qt: :: #!/bin/bash export CHECKBOX_DATA=${CHECKBOX_DATA:-~/.checkbox} export CHECKBOX_SHARE=${CHECKBOX_SHARE:-/usr/share/checkbox} export CHECKBOX_OPTIONS=${CHECKBOX_OPTIONS:---log-level=debug --log=$CHECKBOX_DATA/checkbox-project.log} export CHECKBOX_CERTIFICATION_SHARE=${CHECKBOX_CERTIFICATION_SHARE:-/usr/share/checkbox-certification} export CHECKBOX_OEM_SHARE=${CHECKBOX_PROJECT_BASE_SHARE:-/usr/share/checkbox-project-base} export CHECKBOX_PROJECT_SHARE=${CHECKBOX_PROJECT_SHARE:-/usr/share/checkbox-project} # Convenience for defining the PYTHONPATH directory. if [ "$CHECKBOX_SHARE" != "/usr/share/checkbox" ]; then export PYTHONPATH="$CHECKBOX_SHARE:$PYTHONPATH" fi python3 $CHECKBOX_SHARE/run "$@" $CHECKBOX_PROJECT_SHARE/configs/$(basename $0).ini Here you can see that it defines some locations and an important part is the final python3 line, where it will locate and use the required .ini config file we saw earlier. This hierarchical organization was very powerful but was also difficult to handle, and also had some limitations. Part of the work we did with checkbox was to integrate all the project-specific plugins into checkbox trunk, this way all the core code is in one place, and the project-specific variants only supply jobs, whitelists, data and configuration, without adding new behavior. New plainbox behavior control ============================= Unlike checkbox, plainbox's core is monolythic, and it has no concept of plugins. This makes it easier to understand and work with. The plainbox core has implementations for all the functions in the old checkbox packages, so no additions are necessary to use features such as submission to certification or report generation. What we call plainbox is the library that implements all the functionality, as can be seen :doc:`here`. Plainbox provides tools to help test developers write and package tests. These are delivered in "providers", which are entities designed to encapsulate test descriptions, custom scripts for testing, whitelists and assorted data. They were designed to allow teams to write and deliver their custom tests without worrying too much about the underlying plainbox code. To get information on how to write tests and providers, see the :ref:`Provider Tutorial` However, when actually using these tests to verify a real system, we wanted to provide something easier and closer to the user experience of checkbox. We created two clients, checkbox-gui and checkbox-cli, which had some hardcoded behaviors, and we also started creating other clients which were based on these but were purpose specific. For instance, we had a version of checkbox for SRU testing, another for server certification, and so on. But then we realized that a lot of the code was duplicated and the behaviors were common except for a few changes. So we came up with the concept of "launchers", which are somewhat similar to checkbox's configuration files and shell script launchers. The idea is that checkbox-gui and checkbox-cli have some very basic behaviors, since they are the clients that are shipped by default with ubuntu. They can show all the available whitelists, show a predefined welcome message, and at the end will let the user see the html report and submit it to launchpad using their e-mail address, similar to the version of checkbox that shipped with Ubuntu. Instead of using complicated command line switches, launchers allow you to configure some optional behaviors to customize your testing experience. A launcher contains settings, and is similar to a shell script, but the interpreter will be either checkbox-gui or checkbox-launcher. Here are a few examples of what can be done with launchers. As a surprise, checkbox-cli is itself a launcher: :: #!/usr/bin/env checkbox-launcher [welcome] text = Welcome to System Testing! Checkbox provides tests to confirm that your system is working properly. Once you are finished running the tests, you can view a summary report for your system. Warning: Some tests could cause your system to freeze or become unresponsive. Please save all your work and close all other running applications before beginning the testing process. [suite] whitelist_filter = ^default$ whitelist_selection = ^default$ skip_whitelist_selection = True [transport] submit_to = launchpad You can see here we customize a few options: it shows a welcome message, automatically selects the default whitelist, and will submit to launchpad when it's finished. A graphical launcher example is canonical-certification-client. :: #!/usr/bin/checkbox-gui [welcome] title = "System Certification" text = "

Welcome to System Certification!

This application will gather information from your system. Then you will be asked manual tests to confirm that the system is working properly. Finally, you will be asked for the Secure ID of the computer to submit the information to the certification database.

To learn how to create or locate the Secure ID, please see here: certification.canonical.com

" [suite] whitelist_filter = "^client-(cert|selftest).*" [submission] input_type = "regex" input_placeholder = "Secure ID (15 or 18 characters)" ok_btn_text = "Submit Results" submit_to_hexr = "true" [exporter] xml_export_path = "/tmp/submission.xml" [transport] submit_to = "certification" Graphical launchers are a bit more complicated, but essentially it's similar, what it allows is for you to define some parameters to customize your testing experience. A very simple text-mode launcher is canonical-hw-collection which just runs the basic hardware information tests and uploads them to a hardware database: :: [welcome] title = Gathering hardware information text = Gathering hardware information. You may be prompted for your password. This process will take approximately 30 seconds and you will be provided with a URL through which you can confirm and register your hardware submission. [suite] whitelist_filter = ^hwsubmit$ whitelist_selection = ^hwsubmit$ skip_whitelist_selection = True skip_test_selection = True [submission] # A bogus secure_id ensures we don't ask it # It can always be overridden in the .conf file. secure_id = 000 [transport] submit_to = certification submit_url = https://hardware-server.example.com/ FInally, canonical-driver-test-suite provides both a graphical and a text mode launcher, which are functionally equivalent: :: #!/usr/bin/checkbox-gui [welcome] title = "Canonical Driver Test Suite" text = "

Welcome to the Canonical Driver Test Suite.

This program contains automated and manual tests to help you discover issues that will arise when running your device drivers on Ubuntu.

This application will step the user through these tests in a predetermined order and automatically collect both system information as well as test results. It will also prompt the user for input when manual testing is required.

The run time for the tests is determined by which tests you decide to execute. The user will have the opportunity to customize the test run to accommodate the driver and the amount of time available for testing.

To begin, simply click the Continue button below and follow the onscreen instructions.

" [suite] whitelist_filter = "^ihv-.*" [submission] ok_btn_text = "Save Results" input_type = "none" [exporter] xml_export_path = "" [transport] submit_to = "local" Text mode: :: #!/usr/bin/env checkbox-launcher [welcome] text = Welcome to the Canonical Driver Test Suite This program contains automated and manual tests to help you discover issues that will arise when running your device drivers on Ubuntu. This application will step the user through these tests in a predetermined order and automatically collect both system information as well as test results. It will also prompt the user for input when manual testing is required. The run time for the tests is determined by which tests you decide to execute. The user will have the opportunity to customize the test run to accommodate the driver and the amount of time available for testing. To begin, simply click the Continue button below and follow the onscreen instructions. [suite] # Whitelist(s) displayed in the suite selection screen whitelist_filter = ^ihv-.* # Whitelist_selection is mandatory so we set it to a bogus value so # no whitelists are preselected. whitelist_selection = bogus checkbox-ng-0.23/docs/conf.py0000664000175000017500000002247112627266441016675 0ustar pierrepierre00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CheckboxNG documentation build configuration file, created by # sphinx-quickstart on Wed Feb 13 11:18:39 2013. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys try: import plainbox except ImportError as exc: raise SystemExit("plainbox has to be importable") else: # Inject mock modules so that we can build the # documentation without having the real stuff available from plainbox.vendor import mock for mod_name in ['lxml', 'xlsxwriter', 'requests', 'requests.exceptions', 'dbus', 'dbus.lowlevel', 'dbus.exceptions', 'dbus._compat', 'dbus.service', '_dbus_bindings']: sys.modules[mod_name] = mock.Mock() print("Mocked {}".format(mod_name)) try: import checkbox_ng except ImportError: raise SystemExit("checkbox_ng has to be importable") # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx'] def check_object_path(key, url, path): if os.path.isfile(path): return {key: (url, path)} else: return {key: (url, None)} intersphinx_mapping = {} intersphinx_mapping.update( check_object_path( 'python', 'http:/docs.python.org/', '/usr/share/doc/python{}/html/objects.inv'.format( '.'.join([str(x) for x in sys.version_info[0:2]])))) intersphinx_mapping.update( check_object_path( 'plainbox', 'http://plainbox.readthedocs.org/en/latest/', '/usr/share/doc/python3-plainbox-doc/html/objects.inv')) # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'CheckboxNG' copyright = '2013-2014, Zygmunt Krynicki' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "{0[0]}.{0[1]}".format(checkbox_ng.__version__) # The full version, including alpha/beta/rc tags. release = "{0[0]}.{0[1]}.{0[2]}.{0[3]}.{0[4]}".format(checkbox_ng.__version__) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output ------------------------------------------------- html_theme_path = ['_templates'] html_theme = 'ubuntu1204' html_theme_options = {} # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'CheckboxNGdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, # documentclass [howto/manual]). latex_documents = [ ('index', 'CheckboxNG.tex', 'CheckboxNG Documentation', 'Zygmunt Krynicki', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'checkbox_ng', 'CheckboxNG Documentation', ['Zygmunt Krynicki'], 1), ('stack', 'checkbox-stack', 'description of the checkbox stack', ['Zygmunt Krynicki'], 1), ] # If true, show URL addresses after external links. man_show_urls = True # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'CheckboxNG', 'CheckboxNG Documentation', 'Zygmunt Krynicki', 'CheckboxNG', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' checkbox-ng-0.23/contrib/0000775000175000017500000000000012633675304016077 5ustar pierrepierre00000000000000checkbox-ng-0.23/contrib/checkbox-ci-mailer.service0000664000175000017500000000144012627266441023107 0ustar pierrepierre00000000000000[Unit] Description=CheckBox SRU mini CI mailer # CheckBox mini CI mailer. # # This waits for a "checkbox-sru-finished" event and then # uses curl to post one of two possible log files # to a configurable CGI URL. The CGI can do whatever it # wants, such as emailing the report. # # An /etc/default/plainbox-ci-mailer config file # with the SUBMIT_CGI variable defined is expected. [Service] Type=oneshot #Type=simple # It does not work with this Environment=CHECKBOX_UPSTART_LOG=/tmp/checkbox-server.log Environment=CHECKBOX_DESKTOP_LOG=/tmp/checkbox.log ExecStartPre=/bin/sh -ec '[ -f /etc/default/plainbox-ci-mailer ] || exit 1' ExecStartPre=/bin/sh -ec '[ -x /usr/bin/curl ] || exit 1' ExecStart=/bin/rm -f /etc/xdg/autostart/checkbox-sru.desktop ExecStart=/usr/bin/checkbox-ci-script.sh mailer checkbox-ng-0.23/contrib/checkbox-ci-installed-notifier.service0000664000175000017500000000154212627266441025435 0ustar pierrepierre00000000000000[Unit] Description=CheckBox SRU mini CI notifier After=network-online.target # CheckBox mini CI notifier. # # This waits for a the "Network is Online" target and then # uses curl to post the test starting notification # to a configurable CGI URL. The CGI can do whatever it # wants, such as checking the test is run or not. # # An /etc/default/plainbox-ci-mailer config file # with the SUBMIT_CGI variable defined is expected. [Service] Type=oneshot #Type=simple # It does not work with this Environment=CHECKBOX_SERVER_CONF=/lib/systemd/system/checkbox-sru.service Environment=CHECKBOX_DESKTOP_XDG=/etc/xdg/autostart/checkbox-sru.desktop ExecStartPre=/bin/sh -ec '[ -f /etc/default/plainbox-ci-mailer ] || exit 1' ExecStartPre=/bin/sh -ec '[ -x /usr/bin/curl ] || exit 1' ExecStart=/usr/bin/checkbox-ci-script.sh notification [Install] WantedBy=multi-user.target checkbox-ng-0.23/contrib/checkbox-sru.service0000664000175000017500000000133712627266441022063 0ustar pierrepierre00000000000000[Unit] Description=CheckBox SRU on server After=network-online.target After=checkbox-ci-installed-notifier.service # checkbox sru - Run CheckBox SRU tests after booting # # Run SRU testing with CheckBoxNG after networking # has started and connection available. [Service] Type=oneshot ExecStartPre=/bin/sh -c "/usr/bin/checkbox check-config || exit 1" ExecStartPre=/bin/mkdir -p /var/cache/plainbox ExecStart=/bin/systemctl start checkbox-ci-installed-notifier.service ExecStart=/bin/sh -c "/usr/bin/checkbox sru > /tmp/checkbox-server.log 2>&1" ExecStopPost=/bin/systemctl start checkbox-ci-mailer.service [Install] # This is roughly equivalent to "start on runlevel [2345]" WantedBy=multi-user.target #stop on runlevel [!023456] checkbox-ng-0.23/contrib/com.canonical.certification.PlainBox1.service0000664000175000017500000000013212627266441026600 0ustar pierrepierre00000000000000[D-BUS Service] Name=com.canonical.certification.PlainBox1 Exec=/usr/bin/checkbox service checkbox-ng-0.23/setup.py0000775000175000017500000000522312633675303016155 0ustar pierrepierre00000000000000#!/usr/bin/env python3 # This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . # To avoid an error in atexit._run_exitfuncs while running tests: import concurrent.futures import os import sys from setuptools import setup, find_packages if "test" in sys.argv: # Reset locale for setup.py test os.environ["LANG"] = "" os.environ["LANGUAGE"] = "" os.environ["LC_ALL"] = "C.UTF-8" base_dir = os.path.dirname(__file__) # Load the README.rst file relative to the setup file with open(os.path.join(base_dir, "README.rst"), encoding="UTF-8") as stream: long_description = stream.read() # Check if we are running on readthedocs.org builder. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' # When building on readthedocs.org, skip all real dependencies as those are # mocked away in 'plainbox/docs/conf.py'. This speeds up the build process. # and makes it independent on any packages that are hard to get in a virtualenv if on_rtd: install_requires = [] else: install_requires = [ 'checkbox-support >= 0.2', 'guacamole >= 0.9', 'plainbox >= 0.5.3', 'requests >= 1.0', ] setup( name="checkbox-ng", version="0.23", url="https://launchpad.net/checkbox-ng/", packages=find_packages(), author="Zygmunt Krynicki", test_suite='checkbox_ng.tests.test_suite', author_email="zygmunt.krynicki@canonical.com", license="GPLv3", description="Checkbox - Command Line Test Runner", long_description=long_description, install_requires=install_requires, scripts = ['launchers/checkbox-cli'], entry_points={ 'console_scripts': [ 'checkbox=checkbox_ng.main:main', 'checkbox-submit=checkbox_ng.main:submit', 'checkbox-launcher=checkbox_ng.main:launcher', ], 'plainbox.transport': [ 'certification=' 'checkbox_ng.certification:CertificationTransport', 'launchpad=' 'checkbox_ng.launchpad:LaunchpadTransport', ], }, include_package_data=True) checkbox-ng-0.23/checkbox_ng/0000775000175000017500000000000012633675304016711 5ustar pierrepierre00000000000000checkbox-ng-0.23/checkbox_ng/main.py0000664000175000017500000000332112627266441020207 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2012-2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.main` -- entry points for command line tools ============================================================== """ import logging from plainbox.impl.logging import setup_logging from checkbox_ng.tools import CheckboxLauncherTool from checkbox_ng.tools import CheckboxSubmitTool from checkbox_ng.tools import CheckboxTool logger = logging.getLogger("checkbox.ng.main") def main(argv=None): """ checkbox command line utility """ raise SystemExit(CheckboxTool().main(argv)) def submit(argv=None): """ checkbox-submit command line utility """ raise SystemExit(CheckboxSubmitTool().main(argv)) def launcher(argv=None): """ checkbox-launcher command line utility """ raise SystemExit(CheckboxLauncherTool().main(argv)) # Setup logging before anything else starts working. # If we do it in main() or some other place then unit tests will see # "leaked" log files which are really closed when the runtime shuts # down but not when the tests are finishing setup_logging() checkbox-ng-0.23/checkbox_ng/tests.py0000664000175000017500000000276012627266441020433 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2012 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.tests` -- auxiliary test loaders for checkbox-ng ================================================================== """ import inspect import os import unittest import checkbox_ng def load_unit_tests(): """ Load all unit tests and return a TestSuite object """ # Discover all unit tests. By simple convention those are kept in # python modules that start with the word 'test_' . return unittest.defaultTestLoader.discover( os.path.dirname( inspect.getabsfile(checkbox_ng))) def test_suite(): """ Test suite function used by setuptools test loader. Uses unittest test discovery system to get a list of test cases defined inside checkbox-ng. See setup.py setup(test_suite=...) for a matching entry """ return load_unit_tests() checkbox-ng-0.23/checkbox_ng/test_certification.py0000664000175000017500000001740512627266441023155 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2012, 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # Daniel Manrique # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ plainbox.impl.transport.test_certification ========================================== Test definitions for plainbox.impl.certification module """ from io import BytesIO from unittest import TestCase from pkg_resources import resource_string from plainbox.impl.applogic import PlainBoxConfig from plainbox.impl.transport import TransportError from plainbox.vendor import mock from plainbox.vendor.mock import MagicMock from requests.exceptions import ConnectionError, InvalidSchema, HTTPError import requests from checkbox_ng.certification import CertificationTransport from checkbox_ng.certification import InvalidSecureIDError class CertificationTransportTests(TestCase): # URL are just here to exemplify, since we mock away all network access, # they're not really used. valid_url = "https://certification.canonical.com/submissions/submit" invalid_url = "htz://:3128" unreachable_url = "http://i.dont.exist" valid_secure_id = "a00D000000Kkk5j" valid_option_string = "secure_id={}".format(valid_secure_id) def setUp(self): self.sample_xml = BytesIO(resource_string( "plainbox", "test-data/xml-exporter/example-data.xml" )) self.patcher = mock.patch('requests.post') self.mock_requests = self.patcher.start() def test_parameter_parsing(self): # Makes sense since I'm overriding the base class's constructor. transport = CertificationTransport( self.valid_url, self.valid_option_string) self.assertEqual(self.valid_url, transport.url) self.assertEqual(self.valid_secure_id, transport.options['secure_id']) def test_submit_to_hexr_interpretation(self): transport = CertificationTransport( self.valid_url, "submit_to_hexr=1") self.assertTrue(transport._submit_to_hexr is True) def test_invalid_length_secure_id_are_rejected(self): for length in (14, 16, 20): dummy_id = "a" * length option_string = "secure_id={}".format(dummy_id) with self.assertRaises(InvalidSecureIDError): CertificationTransport(self.valid_url, option_string) def test_invalid_characters_in_secure_id_are_rejected(self): option_string = "secure_id=aA0#" with self.assertRaises(InvalidSecureIDError): CertificationTransport(self.valid_url, option_string) def test_invalid_url(self): transport = CertificationTransport( self.invalid_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.side_effect = InvalidSchema with self.assertRaises(TransportError): result = transport.send(dummy_data) self.assertIsNotNone(result) requests.post.assert_called_with( self.invalid_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=None) @mock.patch('checkbox_ng.certification.logger') def test_valid_url_cant_connect(self, mock_logger): transport = CertificationTransport( self.unreachable_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.side_effect = ConnectionError with self.assertRaises(TransportError): result = transport.send(dummy_data) self.assertIsNotNone(result) requests.post.assert_called_with(self.unreachable_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=None) @mock.patch('checkbox_ng.certification.logger') def test_share_with_hexr_header_sent(self, mock_logger): transport = CertificationTransport( self.valid_url, self.valid_option_string+",submit_to_hexr=1") dummy_data = BytesIO(b"some data to send") result = transport.send(dummy_data) self.assertIsNotNone(result) requests.post.assert_called_with(self.valid_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id, 'X-Share-With-HEXR': True}, proxies=None) def test_send_success(self): transport = CertificationTransport( self.valid_url, self.valid_option_string) requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 200 requests.post.return_value.text = '{"id": 768}' result = transport.send(self.sample_xml) self.assertTrue(result) def test_send_failure(self): transport = CertificationTransport( self.valid_url, self.valid_option_string) requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 412 requests.post.return_value.text = 'Some error' # Oops, raise_for_status doesn't get fooled by my mocking, # so I have to mock *that* method as well.. requests.post.return_value.raise_for_status = MagicMock( side_effect=HTTPError) with self.assertRaises(TransportError): transport.send(self.sample_xml) def proxy_test(self, environment, proxies): test_environment = environment test_proxies = proxies test_config = PlainBoxConfig() test_config.environment = test_environment transport = CertificationTransport( self.valid_url, self.valid_option_string) dummy_data = BytesIO(b"some data to send") requests.post.return_value = MagicMock(name='response') requests.post.return_value.status_code = 200 requests.post.return_value.text = '{"id": 768}' result = transport.send(dummy_data, config=test_config) self.assertTrue(result) requests.post.assert_called_with( self.valid_url, files={'data': dummy_data}, headers={'X_HARDWARE_ID': self.valid_secure_id}, proxies=test_proxies) def test_set_only_one_proxy(self): test_environment = {'http_proxy': "http://1.2.3.4:5"} test_proxies = {'http': "http://1.2.3.4:5"} self.proxy_test(test_environment, test_proxies) def test_set_two_proxies(self): test_environment = {'http_proxy': "http://1.2.3.4:5", 'https_proxy': "http://1.2.3.4:6"} test_proxies = {'http': "http://1.2.3.4:5", 'https': "http://1.2.3.4:6"} self.proxy_test(test_environment, test_proxies) def test_behavior_with_extraneous_environment(self): test_environment = {'http_proxy': "http://1.2.3.4:5", 'weird_value': 'What is this'} test_proxies = {'http': "http://1.2.3.4:5"} self.proxy_test(test_environment, test_proxies) checkbox-ng-0.23/checkbox_ng/tools.py0000664000175000017500000001044612627266441020431 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2012-2015 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.tools` -- top-level command line tools ======================================================== """ import logging import os from plainbox.impl.clitools import SingleCommandToolMixIn from plainbox.impl.clitools import ToolBase from plainbox.impl.commands.cmd_selftest import SelfTestCommand from plainbox.public import get_providers from checkbox_ng import __version__ as version from checkbox_ng.config import CheckBoxConfig from checkbox_ng.tests import load_unit_tests logger = logging.getLogger("checkbox.ng.tools") class CheckboxToolBase(ToolBase): """ Base class for all checkbox-ng tools. This class contains some shared code like configuration, providers, i18n and version handling. """ def _load_config(self): return self.get_config_cls().get() def _load_providers(self): return get_providers() @classmethod def get_exec_version(cls): """ Get the version of the checkbox-ng package """ return cls.format_version_tuple(version) @classmethod def get_config_cls(cls): """ Get particular sub-class of the Config class to use """ return CheckBoxConfig def get_gettext_domain(self): """ Get the 'checkbox-ng' gettext domain """ return "checkbox-ng" def get_locale_dir(self): """ Get an optional development locale directory specific to checkbox-ng """ return os.getenv("CHECKBOX_NG_LOCALE_DIR", None) class CheckboxTool(CheckboxToolBase): """ Tool that implements the new checkbox command. This tool has two sub-commands: checkbox sru - to run stable release update testing checkbox check-config - to validate and display system configuration """ @classmethod def get_exec_name(cls): return "checkbox" def add_subcommands(self, subparsers, early_ns=None): from checkbox_ng.commands.launcher import LauncherCommand from checkbox_ng.commands.sru import SRUCommand from checkbox_ng.commands.submit import SubmitCommand from plainbox.impl.commands.cmd_check_config import CheckConfigCommand SRUCommand( self._load_providers, self._load_config ).register_parser(subparsers) CheckConfigCommand( self._load_config ).register_parser(subparsers) SubmitCommand( self._load_config ).register_parser(subparsers) LauncherCommand( self._load_providers, self._load_config ).register_parser(subparsers) SelfTestCommand(load_unit_tests).register_parser(subparsers) class CheckboxSubmitTool(SingleCommandToolMixIn, CheckboxToolBase): """ A tool class that implements checkbox-submit. This tool implements the submit feature to send test results to the Canonical certification website """ @classmethod def get_exec_name(cls): return "checkbox-submit" def get_command(self): from checkbox_ng.commands.submit import SubmitCommand return SubmitCommand(self._load_config) class CheckboxLauncherTool(SingleCommandToolMixIn, CheckboxToolBase): """ A tool class that implements checkbox-launcher. This tool implements configurable text-mode-graphics launchers that perform a pre-defined testing session based on the launcher profile. """ @classmethod def get_exec_name(cls): return "checkbox-launcher" def get_command(self): from checkbox_ng.commands.launcher import LauncherCommand return LauncherCommand(self._load_providers, self._load_config) checkbox-ng-0.23/checkbox_ng/ui.py0000664000175000017500000003163712627266441017713 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013-2015 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.ui` -- user interface elements ================================================ """ from gettext import gettext as _ from logging import getLogger import textwrap from plainbox.vendor.textland import DrawingContext from plainbox.vendor.textland import EVENT_KEYBOARD from plainbox.vendor.textland import EVENT_RESIZE from plainbox.vendor.textland import Event from plainbox.vendor.textland import IApplication from plainbox.vendor.textland import Size from plainbox.vendor.textland import TextImage from plainbox.vendor.textland import NORMAL, REVERSE logger = getLogger("checkbox.ng.ui") class ShowWelcome(IApplication): """ Display a welcome message """ def __init__(self, text): self.image = TextImage(Size(0, 0)) self.text = text def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD and event.data.key == "enter": raise StopIteration self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) i = 0 ctx.border() for paragraph in self.text.splitlines(): i += 1 for line in textwrap.fill( paragraph, self.image.size.width - 8, replace_whitespace=False).splitlines(): ctx.move_to(4, i) ctx.print(line) i += 1 ctx.move_to(4, i + 1) ctx.attributes.style = REVERSE ctx.print(_("< Continue >")) class ShowMenu(IApplication): """ Display the appropriate menu and return the selected options """ def __init__(self, title, menu, selection=[0]): self.image = TextImage(Size(0, 0)) self.title = title self.menu = menu self.option_count = len(menu) self.position = 0 # Zero-based index of the selected menu option if self.option_count: self.selection = selection else: self.selection = [] def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD: if event.data.key == "down": if self.position < self.option_count: self.position += 1 else: self.position = 0 elif event.data.key == "up": if self.position > 0: self.position -= 1 else: self.position = self.option_count elif (event.data.key == "enter" and self.position == self.option_count): raise StopIteration(self.selection) elif event.data.key == "space": if self.position in self.selection: self.selection.remove(self.position) elif self.position < self.option_count: self.selection.append(self.position) self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) ctx.border(tm=1) ctx.attributes.style = REVERSE ctx.print(' ' * self.image.size.width) ctx.move_to(1, 0) ctx.print(self.title) # Display all the menu items for i in range(self.option_count): ctx.attributes.style = NORMAL if i == self.position: ctx.attributes.style = REVERSE # Display options from line 3, column 4 ctx.move_to(4, 3 + i) ctx.print("[{}] - {}".format( 'X' if i in self.selection else ' ', self.menu[i].replace('ihv-', '').capitalize())) # Display "OK" at bottom of menu ctx.attributes.style = NORMAL if self.position == self.option_count: ctx.attributes.style = REVERSE # Add an empty line before the last option ctx.move_to(4, 4 + self.option_count) ctx.print("< OK >") class ScrollableTreeNode(IApplication): """ Class used to interact with a SelectableJobTreeNode """ def __init__(self, tree, title): self.image = TextImage(Size(0, 0)) self.tree = tree self.title = title self.top = 0 # Top line number self.highlight = 0 # Highlighted line number def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD: self.image = TextImage(self.image.size) if event.data.key == "up": self._scroll("up") elif event.data.key == "down": self._scroll("down") elif event.data.key == "space": self._selectNode() elif event.data.key == "enter": self._toggleNode() elif event.data.key in 'sS': self.tree.set_descendants_state(True) elif event.data.key in 'dD': self.tree.set_descendants_state(False) elif event.data.key in 'tT': raise StopIteration self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) ctx.border(tm=1, bm=1) cols = self.image.size.width extra_cols = 0 if cols > 80: extra_cols = cols - 80 ctx.attributes.style = REVERSE ctx.print(' ' * cols) ctx.move_to(1, 0) bottom = self.top + self.image.size.height - 4 ctx.print(self.title) ctx.move_to(1, self.image.size.height - 1) ctx.attributes.style = REVERSE ctx.print(_("Enter")) ctx.move_to(6, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print(_(": Expand/Collapse")) ctx.move_to(27, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("S") ctx.move_to(28, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("elect All") ctx.move_to(41, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("D") ctx.move_to(42, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("eselect All") ctx.move_to(66 + extra_cols, self.image.size.height - 1) ctx.print(_("Start ")) ctx.move_to(72 + extra_cols, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("T") ctx.move_to(73 + extra_cols, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("esting") for i, line in enumerate(self.tree.render(cols - 3)[self.top:bottom]): ctx.move_to(2, i + 2) if i != self.highlight: ctx.attributes.style = NORMAL else: # highlight the current line ctx.attributes.style = REVERSE ctx.print(line) def _selectNode(self): """ Mark a node/job as selected for this test run. See :meth:`SelectableJobTreeNode.set_ancestors_state()` and :meth:`SelectableJobTreeNode.set_descendants_state()` for details about the automatic selection of parents and descendants. """ node, category = self.tree.get_node_by_index(self.top + self.highlight) if category: # then the selected node is a job not a category job = node category.job_selection[job] = not(category.job_selection[job]) category.update_selected_state() category.set_ancestors_state(category.job_selection[job]) else: node.selected = not(node.selected) node.set_descendants_state(node.selected) node.set_ancestors_state(node.selected) def _toggleNode(self): """ Expand/collapse a node """ node, is_job = self.tree.get_node_by_index(self.top + self.highlight) if node is not None and not is_job: node.expanded = not(node.expanded) def _scroll(self, direction): visible_length = len(self.tree.render()) # Scroll the tree view if (direction == "up" and self.highlight == 0 and self.top != 0): self.top -= 1 return elif (direction == "down" and (self.highlight + 1) == (self.image.size.height - 4) and (self.top + self.image.size.height - 4) != visible_length): self.top += 1 return # Move the highlighted line if (direction == "up" and (self.top != 0 or self.highlight != 0)): self.highlight -= 1 elif (direction == "down" and (self.top + self.highlight + 1) != visible_length and (self.highlight + 1) != (self.image.size.height - 4)): self.highlight += 1 class ShowRerun(ScrollableTreeNode): """ Display the re-run screen.""" def __init__(self, tree, title): super().__init__(tree, title) def consume_event(self, event: Event): if event.kind == EVENT_RESIZE: self.image = TextImage(event.data) # data is the new size elif event.kind == EVENT_KEYBOARD: self.image = TextImage(self.image.size) if event.data.key == "up": self._scroll("up") elif event.data.key == "down": self._scroll("down") elif event.data.key == "space": self._selectNode() elif event.data.key == "enter": self._toggleNode() elif event.data.key in 'sS': self.tree.set_descendants_state(True) elif event.data.key in 'dD': self.tree.set_descendants_state(False) elif event.data.key in 'fF': self.tree.set_descendants_state(False) raise StopIteration elif event.data.key in 'rR': raise StopIteration self.repaint(event) return self.image def repaint(self, event: Event): ctx = DrawingContext(self.image) ctx.border(tm=1, bm=1) cols = self.image.size.width extra_cols = 0 if cols > 80: extra_cols = cols - 80 ctx.attributes.style = REVERSE ctx.print(' ' * cols) ctx.move_to(1, 0) bottom = self.top + self.image.size.height - 4 ctx.print(self.title) ctx.move_to(1, self.image.size.height - 1) ctx.attributes.style = REVERSE ctx.print(_("Enter")) ctx.move_to(6, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print(_(": Expand/Collapse")) ctx.move_to(27, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("S") ctx.move_to(28, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("elect All") ctx.move_to(41, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("D") ctx.move_to(42, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("eselect All") ctx.move_to(63 + extra_cols, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("F") ctx.move_to(64 + extra_cols, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print(_("inish")) ctx.move_to(73 + extra_cols, self.image.size.height - 1) ctx.attributes.style = REVERSE # FIXME: i18n problem ctx.print("R") ctx.move_to(74 + extra_cols, self.image.size.height - 1) ctx.attributes.style = NORMAL ctx.print("e-run") for i, line in enumerate(self.tree.render(cols - 3)[self.top:bottom]): ctx.move_to(2, i + 2) if i != self.highlight: ctx.attributes.style = NORMAL else: # highlight the current line ctx.attributes.style = REVERSE ctx.print(line) checkbox-ng-0.23/checkbox_ng/config.py0000664000175000017500000000650412627266441020536 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.config` -- CheckBoxNG configuration ===================================================== """ from gettext import gettext as _ import itertools import os from plainbox.impl.applogic import PlainBoxConfig from plainbox.impl.secure import config SECURE_ID_PATTERN = r"^[a-zA-Z0-9]{15}$|^[a-zA-Z0-9]{18}$" class CheckBoxConfig(PlainBoxConfig): """ Configuration for checkbox-ng """ secure_id = config.Variable( section="sru", help_text=_("Secure ID of the system"), validator_list=[config.PatternValidator(SECURE_ID_PATTERN)]) submit_to_c3 = config.Variable( section="submission", help_text=_("Whether to send the submission data to c3")) submit_to_hexr = config.Variable( section="submission", help_text=_("Whether to also send the submission data to HEXR"), kind=bool) # TODO: Add a validator to check if email looks fine email_address = config.Variable( section="sru", help_text=_("Email address to log into the Launchpad HWDB")) # TODO: Add a validator to check if URL looks fine c3_url = config.Variable( section="sru", help_text=_("URL of the certification website"), default="https://certification.canonical.com/submissions/submit/") # TODO: Add a validator to check if URL looks fine lp_url = config.Variable( section="sru", help_text=_("URL of the launchpad hardware database"), default="https://launchpad.net/+hwdb/+submit") fallback_file = config.Variable( section="sru", help_text=_("Location of the fallback file")) whitelist = config.Variable( section="sru", help_text=_("Optional whitelist with which to run SRU testing")) test_plan = config.Variable( section="sru", help_text=_("Optional test plan with which to run SRU testing")) staging = config.Variable( section="sru", kind=bool, default=False, help_text=_("Send the data to non-production test server")) class Meta(PlainBoxConfig.Meta): # TODO: properly depend on xdg and use real code that also handles # XDG_CONFIG_HOME. # # NOTE: filename_list is composed of checkbox and plainbox variables, # mixed so that: # - checkbox takes precedence over plainbox # - ~/.config takes precedence over /etc filename_list = list( itertools.chain( *zip( PlainBoxConfig.Meta.filename_list, ( '/etc/xdg/checkbox.conf', os.path.expanduser('~/.config/checkbox.conf'))))) checkbox-ng-0.23/checkbox_ng/launcher.py0000664000175000017500000000750412627266441021073 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.launcher` -- launcher definition ================================================== """ from gettext import gettext as _ import logging from checkbox_ng.config import SECURE_ID_PATTERN from plainbox.impl.secure import config from plainbox.impl.transport import get_all_transports logger = logging.getLogger("checkbox.ng.launcher") class LauncherDefinition(config.Config): """ Launcher definition. Launchers are small executables using one of the available user interfaces as the interpreter. This class contains all the available options that can be set inside the launcher, that will affect the user interface at runtime. """ title = config.Variable( section="welcome", help_text=_("Application Title")) text = config.Variable( section="welcome", help_text=_("Welcome Message")) whitelist_filter = config.Variable( section="suite", # TODO: valid regexp text validator help_text=_("Pattern that whitelists need to match to be displayed")) whitelist_selection = config.Variable( section="suite", # TODO: valid regexp text validator help_text=_("Pattern that whitelists need to match to be selected")) skip_whitelist_selection = config.Variable( section="suite", kind=bool, default=False, help_text=_("If enabled then suite selection screen is not displayed")) skip_test_selection = config.Variable( section="suite", kind=bool, default=False, help_text=_("If enabled then test selection screen is not displayed")) input_type = config.Variable( section="submission", # TODO: probably a choice validator help_text=_("Type of the input field?")) ok_btn_text = config.Variable( section="submission", help_text=_("Label on the 'send' button")) submit_to_hexr = config.Variable( section="submission", kind=bool, # TODO: default? help_text=_("If enabled then test results will be also sent to HEXR")) submit_to = config.Variable( section="transport", validator_list=[config.ChoiceValidator(get_all_transports().keys())], help_text=_("Where to submit the test results to")) # TODO: Add a validator to ensure it looks like a valid URL submit_url = config.Variable( section="transport", help_text=_("HTTP endpoint to submit data to, using the" " transport specified with submit_to.")) secure_id = config.Variable( section="submission", validator_list=[config.PatternValidator(SECURE_ID_PATTERN)], help_text=_("Secure ID to identify the system this" " submission belongs to.")) config_filename = config.Variable( section="config", help_text=_("Name of custom configuration file")) dont_suppress_output = config.Variable( section="ui", kind=bool, default=False, help_text=_("Don't suppress the output of certain job plugin types.")) exporter = config.Section( help_text=_("Section with only exported unit ids as keys (no values)")) checkbox-ng-0.23/checkbox_ng/test_misc.py0000664000175000017500000001571012627266441021262 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ checkbox_ng.commands.test_cli ============================= Test definitions for checkbox_ng.commands.cli module """ from unittest import TestCase from plainbox.impl.session import SessionState from plainbox.impl.testing_utils import make_job from plainbox.impl.unit.job import JobDefinition from checkbox_ng.misc import JobTreeNode from checkbox_ng.misc import SelectableJobTreeNode class TestJobTreeNode(TestCase): def setUp(self): A = make_job('A') B = make_job('B', plugin='local', description='foo') C = make_job('C') D = make_job('D', plugin='shell') E = make_job('E', plugin='local', description='bar') F = make_job('F', plugin='shell') G = make_job('G', plugin='local', description='baz') R = make_job('R', plugin='resource') Z = make_job('Z', plugin='local', description='zaz') state = SessionState([A, B, C, D, E, F, G, R, Z]) # D and E are a child of B state.job_state_map[D.id].via_job = B state.job_state_map[E.id].via_job = B # F is a child of E state.job_state_map[F.id].via_job = E self.tree = JobTreeNode.create_tree( state, [R, B, C, D, E, F, G, A, Z]) def test_create_tree(self): self.assertIsInstance(self.tree, JobTreeNode) self.assertEqual(len(self.tree.categories), 3) [self.assertIsInstance(c, JobTreeNode) for c in self.tree.categories] self.assertEqual(len(self.tree.jobs), 3) [self.assertIsInstance(j, JobDefinition) for j in self.tree.jobs] self.assertIsNone(self.tree.parent) self.assertEqual(self.tree.depth, 0) node = self.tree.categories[1] self.assertEqual(node.name, 'foo') self.assertEqual(len(node.categories), 1) [self.assertIsInstance(c, JobTreeNode) for c in node.categories] self.assertEqual(len(node.jobs), 1) [self.assertIsInstance(j, JobDefinition) for j in node.jobs] class TestSelectableJobTreeNode(TestCase): def setUp(self): self.A = make_job('a', name='A') self.B = make_job('b', name='B', plugin='local', description='foo') self.C = make_job('c', name='C') self.D = make_job('d', name='D', plugin='shell') self.E = make_job('e', name='E', plugin='shell') self.F = make_job('f', name='F', plugin='resource', description='baz') state = SessionState([self.A, self.B, self.C, self.D, self.E, self.F]) # D and E are a child of B state.job_state_map[self.D.id].via_job = self.B state.job_state_map[self.E.id].via_job = self.B self.tree = SelectableJobTreeNode.create_tree(state, [ self.A, self.B, self.C, self.D, self.E, self.F ]) def test_create_tree(self): self.assertIsInstance(self.tree, SelectableJobTreeNode) self.assertEqual(len(self.tree.categories), 1) [self.assertIsInstance(c, SelectableJobTreeNode) for c in self.tree.categories] self.assertEqual(len(self.tree.jobs), 2) [self.assertIsInstance(j, JobDefinition) for j in self.tree.jobs] self.assertTrue(self.tree.selected) [self.assertTrue(self.tree.job_selection[j]) for j in self.tree.job_selection] self.assertTrue(self.tree.expanded) self.assertIsNone(self.tree.parent) self.assertEqual(self.tree.depth, 0) def test_get_node_by_index(self): self.assertEqual(self.tree.get_node_by_index(0)[0].name, 'foo') self.assertEqual(self.tree.get_node_by_index(1)[0].name, 'D') self.assertEqual(self.tree.get_node_by_index(2)[0].name, 'E') self.assertEqual(self.tree.get_node_by_index(3)[0].name, 'A') self.assertEqual(self.tree.get_node_by_index(4)[0].name, 'C') self.assertIsNone(self.tree.get_node_by_index(5)[0]) def test_render(self): expected = ['[X] - foo', '[X] d', '[X] e', '[X] a', '[X] c'] self.assertEqual(self.tree.render(), expected) def test_render_deselected_all(self): self.tree.set_descendants_state(False) expected = ['[ ] - foo', '[ ] d', '[ ] e', '[ ] a', '[ ] c'] self.assertEqual(self.tree.render(), expected) def test_render_reselected_all(self): self.tree.set_descendants_state(False) self.tree.set_descendants_state(True) expected = ['[X] - foo', '[X] d', '[X] e', '[X] a', '[X] c'] self.assertEqual(self.tree.render(), expected) def test_render_with_child_collapsed(self): self.tree.categories[0].expanded = False expected = ['[X] + foo', '[X] a', '[X] c'] self.assertEqual(self.tree.render(), expected) def test_set_ancestors_state(self): self.tree.set_descendants_state(False) node = self.tree.categories[0] node.job_selection[self.E] = True node.update_selected_state() node.set_ancestors_state(node.selected) expected = ['[X] - foo', '[ ] d', '[X] e', '[ ] a', '[ ] c'] self.assertEqual(self.tree.render(), expected) node.selected = not(node.selected) node.set_ancestors_state(node.selected) node.set_descendants_state(node.selected) expected = ['[ ] - foo', '[ ] d', '[ ] e', '[ ] a', '[ ] c'] self.assertEqual(self.tree.render(), expected) def test_selection(self): self.tree.set_descendants_state(False) node = self.tree.categories[0] node.job_selection[self.D] = True node.update_selected_state() node.set_ancestors_state(node.selected) # Note that in addition to the selected (D) test, we need the # tree selection to contain the resource (F), even though the # user never saw it in the previous tests for visual presentation. self.assertEqual(self.tree.selection, [self.D]) checkbox-ng-0.23/checkbox_ng/__init__.py0000664000175000017500000000157612633675303021032 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng` -- checkbox-ng package ========================================= CheckBoxNG is a new version of CheckBox built on top of PlainBox """ __version__ = (0, 23, 0, "final", 0) checkbox-ng-0.23/checkbox_ng/certification.py0000664000175000017500000001712612627266441022116 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # Daniel Manrique # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox.certification` -- plainbox transport to certification database ============================================================================= This module contains a PlainBox transport that knows how to send the certification XML data to the Canonical certification database. """ from gettext import gettext as _ from logging import getLogger import re from plainbox.impl.secure.config import Unset from plainbox.impl.transport import TransportBase from plainbox.impl.transport import TransportError import requests from checkbox_ng.config import SECURE_ID_PATTERN logger = getLogger("checkbox.ng.certification") class InvalidSecureIDError(ValueError): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class CertificationTransport(TransportBase): """ Transport for sending data to certification database. - POSTs data to a http(s) endpoint - Adds a header with a hardware identifier - Data is expected to be in checkbox xml-compatible format. This means it will work best with a stream produced by the xml exporter. """ def __init__(self, where, options): """ Initialize the Certification Transport. The options string may contain 'secure_id' which must be a 15- or 18-character alphanumeric ID for the system. It may also contain a submit_to_hexr boolean, set to 1 to enable submission to hexr. """ super().__init__(where, options) # Interpret this setting here submit_to_hexr = self.options.get('submit_to_hexr') self._submit_to_hexr = False try: if submit_to_hexr and (submit_to_hexr.lower() in ('yes', 'true') or int(submit_to_hexr) == 1): self._submit_to_hexr = True except ValueError: # Just leave it at False pass self._secure_id = self.options.get('secure_id') if self._secure_id is not None: self._validate_secure_id(self._secure_id) def send(self, data, config=None, session_state=None): """ Sends data to the specified server. :param data: Data containing the xml dump to be sent to the server. This can be either bytes or a file-like object (BytesIO works fine too). If this is a file-like object, it will be read and streamed "on the fly". :param config: Optional PlainBoxConfig object. If http_proxy and https_proxy values are set in this config object, they will be used to send data via the specified protocols. Note that the transport also honors the http_proxy and https_proxy environment variables. Proxy string format is http://[user:password@]:port :param session_state: The session for which this transport is associated with the data being sent (optional) :returns: A dictionary with responses from the server if submission was successful. This should contain an 'id' key, however the server response may change, so the only guarantee we make is that this will be non-False if the server accepted the data. Returns empty dictionary otherwise. :raises requests.exceptions.Timeout: If sending timed out. :raises requests.exceptions.ConnectionError: If connection failed outright. :raises requests.exceptions.HTTPError: If the server returned a non-success result code """ proxies = None if config and config.environment is not Unset: proxies = { proto[:-len("_proxy")]: config.environment[proto] for proto in ['http_proxy', 'https_proxy'] if proto in config.environment } # Find the effective value of secure_id: # - use the configuration object (if available) # - override with secure_id= option (if defined) secure_id = None if config is not None and hasattr(config, 'secure_id'): secure_id = config.secure_id if self._secure_id is not None: secure_id = self._secure_id if secure_id is None: raise InvalidSecureIDError(_("Secure ID not specified")) self._validate_secure_id(secure_id) logger.debug( _("Sending to %s, hardware id is %s"), self.url, secure_id) headers = {"X_HARDWARE_ID": secure_id} # Similar handling for submit_to_hexr submit_to_hexr = False if config is not None and hasattr(config, 'submit_to_hexr'): submit_to_hexr = config.submit_to_hexr logger.debug(_("submit_to_hexr set to %s by config"), submit_to_hexr) if self._submit_to_hexr: submit_to_hexr = self._submit_to_hexr logger.debug(_("submit_to_hexr set to %s by UI"), submit_to_hexr) # We could always set this header since hexr will only process a value # of 'True', but this avoids injecting that extraneous knowledge into # the tests. # Note that hexr will only process a submission with this header's # value set to 'True', so this boolean conversion should be ok. if submit_to_hexr: headers["X-Share-With-HEXR"] = submit_to_hexr # Requests takes care of properly handling a file-like data. form_payload = {"data": data} try: response = requests.post( self.url, files=form_payload, headers=headers, proxies=proxies) except requests.exceptions.Timeout as exc: raise TransportError( _("Request to {0} timed out: {1}").format(self.url, exc)) except requests.exceptions.InvalidSchema as exc: raise TransportError( _("Invalid destination URL: {0}").format(exc)) except requests.exceptions.ConnectionError as exc: raise TransportError( _("Unable to connect to {0}: {1}").format(self.url, exc)) if response is not None: try: # This will raise HTTPError for status != 20x response.raise_for_status() except requests.exceptions.RequestException as exc: raise TransportError(str(exc)) logger.debug("Success! Server said %s", response.text) try: return response.json() except Exception as exc: raise TransportError(str(exc)) # ISessionStateTransport.send must return dictionary return {} def _validate_secure_id(self, secure_id): if not re.match(SECURE_ID_PATTERN, secure_id): raise InvalidSecureIDError( _("secure_id must be 15 or 18-character alphanumeric string")) checkbox-ng-0.23/checkbox_ng/misc.py0000664000175000017500000003302612627266441020223 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013-2014 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.misc` -- Other stuff ====================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from logging import getLogger logger = getLogger("checkbox.ng.commands.cli") class JobTreeNode: r""" JobTreeNode class is used to store a tree structure. A tree consists of a collection of JobTreeNode instances connected in a hierarchical way where nodes are used as categories, jobs belonging to a category are listed in the node leaves. Example:: / Job A Root-| | / Job B \--- Category X | \ Job C """ def __init__(self, name=None): """ Initialize the job tree node with a given name. """ self._name = name if name else 'Root' self._parent = None self._categories = [] self._jobs = [] @property def name(self): """ name of this node. """ return self._name @property def parent(self): """ parent node for this node. """ return self._parent @property def categories(self): """ list of sub categories. """ return self._categories @property def jobs(self): """ job(s) belonging to this node/category. """ return self._jobs @property def depth(self): """ level of depth for this node. """ return (self._parent.depth + 1) if self._parent else 0 def __str__(self): """ same as self.name. """ return self.name def __repr__(self): """ Get a representation of this node for debugging. """ return "".format(self.name) def add_category(self, category): """ Add a new category to this node. :param category: The node instance to be added as a category. """ self._categories.append(category) # Always keep this list sorted to easily find a given child by index self._categories.sort(key=lambda item: item.name) category._parent = self def add_job(self, job): """ Add a new job to this node. :param job: The job instance to be added to this node. """ self._jobs.append(job) # Always keep this list sorted to easily find a given leaf by index # Note bisect.insort(a, x) cannot be used here as JobDefinition are # not sortable self._jobs.sort(key=lambda item: item.id) def get_ancestors(self): """ Get the list of ancestors from here to the root of the tree. """ ancestors = [] node = self while node.parent is not None: ancestors.append(node.parent) node = node.parent return ancestors def get_descendants(self): """ Return a list of all descendant category nodes. """ descendants = [] for category in self.categories: descendants.append(category) descendants.extend(category.get_descendants()) return descendants @classmethod def create_tree(cls, session_state, job_list): """ Build a rooted JobTreeNode from a job list. :argument session_state: A session state object :argument job_list: List of jobs to consider for building the tree. """ builder = TreeBuilder(session_state, cls) for job in job_list: builder.auto_add_job(job) return builder.root_node class TreeBuilder: """ Builder for :class:`JobTreeNode`. Helper class that assists in building a tree of :class:`JobTreeNode` objects out of job definitions and their associations, as expressed by :attr:`JobState.via_job` associated with each job. The builder is a single-use object and should be re-created for each new construct. Internally it stores the job_state_map of the :class:`SessionState` it was created with as well as additional helper state. """ def __init__(self, session_state: "SessionState", node_cls): self._job_state_map = session_state.job_state_map self._node_cls = node_cls self._root_node = node_cls() self._category_node_map = {} # id -> node @property def root_node(self): return self._root_node def auto_add_job(self, job): """ Add a job to the tree, automatically creating category nodes as needed. :param job: The job definition to add. """ if job.plugin == 'local': # For local jobs, just create the category node but don't add the # local job itself there. self.get_or_create_category_node(job) else: # For all other jobs, look at the parent job (if any) and create # the category node out of that node. This never fails as "None" is # the root_node object. state = self._job_state_map[job.id] node = self.get_or_create_category_node(state.via_job) # Then add that job to the category node node.add_job(job) def get_or_create_category_node(self, category_job): """ Get a category node for a given job. Get or create a :class:`JobTreeNode` that corresponds to the category defined (somehow) by the job ``category_job``. :param category_job: The job that describes the category. This is either a plugin="local" job or a plugin="resource" job. This can also be None, which is a shorthand to say "root node". :returns: The ``root_node`` if ``category_job`` is None. A freshly created node, created with :func:`create_category_node()` if the category_job was never seen before (as recorded by the category_node_map). """ logger.debug("get_or_create_category_node(%r)", category_job) if category_job is None: return self._root_node if category_job.id not in self._category_node_map: category_node = self.create_category_node(category_job) # The category is added to its parent, that's either the root # (if we're standalone) or the non-root category this one # belongs to. category_state = self._job_state_map[category_job.id] if category_state.via_job is not None: parent_category_node = self.get_or_create_category_node( category_state.via_job) else: parent_category_node = self._root_node parent_category_node.add_category(category_node) else: category_node = self._category_node_map[category_job.id] return category_node def create_category_node(self, category_job): """ Create a category node for a given job. Create a :class:`JobTreeNode` that corresponds to the category defined (somehow) by the job ``category_job``. :param category_job: The job that describes the node to create. :returns: A fresh node with appropriate data. """ logger.debug("create_category_node(%r)", category_job) if category_job.summary == category_job.partial_id: category_node = self._node_cls(category_job.description) else: category_node = self._node_cls(category_job.summary) self._category_node_map[category_job.id] = category_node return category_node class SelectableJobTreeNode(JobTreeNode): """ Implementation of a node in a tree that can be selected/deselected """ def __init__(self, job=None): super().__init__(job) self.selected = True self.job_selection = {} self.expanded = True self.current_index = 0 self._resource_jobs = [] def get_node_by_index(self, index, tree=None): """ Return the node found at the position given by index considering the tree from a top-down list view. """ if tree is None: tree = self if self.expanded: for category in self.categories: if index == tree.current_index: tree.current_index = 0 return (category, None) else: tree.current_index += 1 result = category.get_node_by_index(index, tree) if result != (None, None): return result for job in self.jobs: if index == tree.current_index: tree.current_index = 0 return (job, self) else: tree.current_index += 1 return (None, None) def render(self, cols=80): """ Return the tree as a simple list of categories and jobs suitable for display. Jobs are properly indented to respect the tree hierarchy and selection marks are added automatically at the beginning of each element. The node titles should not exceed the width of a the terminal and thus are cut to fit inside. """ self._flat_list = [] if self.expanded: for category in self.categories: prefix = '[ ]' if category.selected: prefix = '[X]' line = '' title = category.name if category.jobs or category.categories: if category.expanded: line = prefix + self.depth * ' ' + ' - ' + title else: line = prefix + self.depth * ' ' + ' + ' + title else: line = prefix + self.depth * ' ' + ' ' + title if len(line) > cols: col_max = cols - 4 # includes len('...') + a space line = line[:col_max] + '...' self._flat_list.append(line) self._flat_list.extend(category.render(cols)) for job in self.jobs: prefix = '[ ]' if self.job_selection[job]: prefix = '[X]' title = job.summary line = prefix + self.depth * ' ' + ' ' + title if len(line) > cols: col_max = cols - 4 # includes len('...') + a space line = line[:col_max] + '...' self._flat_list.append(line) return self._flat_list def add_job(self, job): if job.plugin == 'resource': # I don't want the user to see resources but I need to keep # track of them to put them in the final selection. I also # don't want to add them to the tree. self._resource_jobs.append(job) return super().add_job(job) self.job_selection[job] = True @property def selection(self): """ Return all the jobs currently selected """ self._selection_list = [] for category in self.categories: self._selection_list.extend(category.selection) for job in self.job_selection: if self.job_selection[job]: self._selection_list.append(job) return self._selection_list @property def resource_jobs(self): """Return all the resource jobs.""" return self._resource_jobs def set_ancestors_state(self, new_state): """ Set the selection state of all ancestors consistently """ # If child is set, then all ancestors must be set if new_state: parent = self.parent while parent: parent.selected = new_state parent = parent.parent # If child is not set, then all ancestors mustn't be set # unless another child of the ancestor is set else: parent = self.parent while parent: if any((category.selected for category in parent.categories)): break if any((parent.job_selection[job] for job in parent.job_selection)): break parent.selected = new_state parent = parent.parent def update_selected_state(self): """ Update the category state according to its job selection """ if any((self.job_selection[job] for job in self.job_selection)): self.selected = True else: self.selected = False def set_descendants_state(self, new_state): """ Set the selection state of all descendants recursively """ self.selected = new_state for job in self.job_selection: self.job_selection[job] = new_state for category in self.categories: category.set_descendants_state(new_state) checkbox-ng-0.23/checkbox_ng/commands/0000775000175000017500000000000012633675304020512 5ustar pierrepierre00000000000000checkbox-ng-0.23/checkbox_ng/commands/cli.py0000664000175000017500000000566512627266441021650 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013-2014 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands.cli` -- Command line sub-command =========================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from argparse import SUPPRESS from gettext import gettext as _ from logging import getLogger from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.commands.cmd_checkbox import CheckBoxCommandMixIn from plainbox.impl.commands.inv_check_config import CheckConfigInvocation from checkbox_ng.commands.newcli import CliInvocation2 logger = getLogger("checkbox.ng.commands.cli") class CliCommand(PlainBoxCommand, CheckBoxCommandMixIn): """ Command for running tests using the command line UI. """ gettext_domain = "checkbox-ng" def __init__(self, provider_loader, config_loader, settings): self.provider_loader = provider_loader self.config_loader = config_loader self.settings = settings def invoked(self, ns): # Run check-config, if requested if ns.check_config: retval = CheckConfigInvocation(self.config_loader).run() return retval return CliInvocation2( self.provider_loader, self.loader_config, ns, self.settings ).run() def register_parser(self, subparsers): parser = subparsers.add_parser(self.settings['subparser_name'], help=self.settings['subparser_help']) parser.set_defaults(command=self) parser.set_defaults(dry_run=False) parser.add_argument( "--check-config", action="store_true", help=_("run check-config")) group = parser.add_argument_group(title=_("user interface options")) parser.set_defaults(color=None) group.add_argument( '--no-color', dest='color', action='store_false', help=SUPPRESS) group.add_argument( '--non-interactive', action='store_true', help=_("skip tests that require interactivity")) group.add_argument( '--dont-suppress-output', action="store_true", default=False, help=_("don't suppress the output of certain job plugin types")) # Call enhance_parser from CheckBoxCommandMixIn self.enhance_parser(parser) checkbox-ng-0.23/checkbox_ng/commands/launcher.py0000664000175000017500000001050312627266441022665 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands.launcher` -- `checkbox launcher` command =================================================================== """ from argparse import SUPPRESS from gettext import gettext as _ import itertools import logging import os from checkbox_ng.commands import CheckboxCommand from checkbox_ng.commands.newcli import CliInvocation2 from checkbox_ng.commands.submit import SubmitCommand from checkbox_ng.config import CheckBoxConfig from checkbox_ng.launcher import LauncherDefinition from plainbox.impl.commands.cmd_checkbox import CheckBoxCommandMixIn logger = logging.getLogger("checkbox.ng.commands.launcher") class LauncherCommand(CheckboxCommand, CheckBoxCommandMixIn, SubmitCommand): """ run a customized testing session This command can be used as an interpreter for the so-called launchers. Those launchers are small text files that define the parameters of the test and can be executed directly to run a customized checkbox-ng testing session. """ def __init__(self, provider_loader, config_loader): self._provider_loader = provider_loader self.config = config_loader() def invoked(self, ns): try: with open(ns.launcher, 'rt', encoding='UTF-8') as stream: first_line = stream.readline() if not first_line.startswith("#!"): stream.seek(0) text = stream.read() except IOError as exc: logger.error(_("Unable to load launcher definition: %s"), exc) return 1 launcher = LauncherDefinition() launcher.read_string(text) if launcher.problem_list: logger.error(_("Unable to start launcher because of errors:")) for problem in launcher.problem_list: logger.error("%s", str(problem)) return 1 # Override the default CheckBox configuration with the one provided # by the launcher self.config.Meta.filename_list = list( itertools.chain( *zip( itertools.islice( CheckBoxConfig.Meta.filename_list, 0, None, 2), itertools.islice( CheckBoxConfig.Meta.filename_list, 1, None, 2), ('/etc/xdg/{}'.format(launcher.config_filename), os.path.expanduser( '~/.config/{}'.format(launcher.config_filename))))) ) self.config.read(self.config.Meta.filename_list) ns.dry_run = False ns.dont_suppress_output = launcher.dont_suppress_output return CliInvocation2( self.provider_loader, lambda: self.config, ns, launcher ).run() def register_parser(self, subparsers): parser = self.add_subcommand(subparsers) self.register_arguments(parser) def register_arguments(self, parser): parser.add_argument( '--no-color', dest='color', action='store_false', help=SUPPRESS) parser.set_defaults(color=None) parser.add_argument( "launcher", metavar=_("LAUNCHER"), help=_("launcher definition file to use")) parser.set_defaults(command=self) parser.conflict_handler = 'resolve' # Call enhance_parser from CheckBoxCommandMixIn self.enhance_parser(parser) group = parser.add_argument_group(title=_("user interface options")) group.add_argument( '--non-interactive', action='store_true', help=_("skip tests that require interactivity")) # Call register_optional_arguments from SubmitCommand self.register_optional_arguments(parser) checkbox-ng-0.23/checkbox_ng/commands/sru.py0000664000175000017500000001470412627266441021704 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands.sru` -- sru sub-command ================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ import sys from gettext import gettext as _ from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.commands.inv_check_config import CheckConfigInvocation from plainbox.impl.ingredients import CanonicalCommand from plainbox.impl.secure.config import ValidationError, Unset class sru(CanonicalCommand): """ Run stable release update (sru) tests. Stable release updates are periodic fixes for nominated bugs that land in existing supported Ubuntu releases. To ensure a certain level of quality all SRU updates affecting hardware enablement are automatically tested on a pool of certified machines. """ def __init__(self, config): """Init method to store the config settings.""" self.config = config if not self.config.test_plan: self.config.test_plan = "2013.com.canonical.certification::sru" def register_arguments(self, parser): """Method called to register command line arguments.""" parser.add_argument( '--secure_id', metavar=_("SECURE-ID"), # NOTE: --secure-id is optional only when set in a config file required=self.config.secure_id is Unset, help=_("Canonical hardware identifier")) parser.add_argument( '-T', '--test-plan', action="store", metavar=_("TEST-PLAN-ID"), default=None, # TRANSLATORS: this is in imperative form help=_("load the specified test plan")) parser.add_argument( '--staging', action='store_true', default=False, help=_("Send the data to non-production test server")) parser.add_argument( "--check-config", action="store_true", help=_("run check-config before starting")) def invoked(self, ctx): """Method called when the command is invoked.""" # Copy command-line arguments over configuration variables try: if ctx.args.secure_id: self.config.secure_id = ctx.args.secure_id if ctx.args.test_plan: self.config.test_plan = ctx.args.test_plan if ctx.args.staging: self.config.staging = ctx.args.staging except ValidationError as exc: print(_("Configuration problems prevent running SRU tests")) print(exc) return 1 ctx.sa.use_alternate_configuration(self.config) # Run check-config, if requested if ctx.args.check_config: retval = CheckConfigInvocation(lambda: self.config).run() if retval != 0: return retval self.transport = self._create_transport( ctx.sa, self.config.secure_id, self.config.staging) self.ctx = ctx try: self._collect_info(ctx.rc, ctx.sa) self._save_results(ctx.rc, ctx.sa) self._send_results( ctx.rc, ctx.sa, self.config.secure_id, self.config.staging) except KeyboardInterrupt: return 1 def _save_results(self, rc, sa): rc.reset() rc.padding = (1, 1, 0, 1) path = sa.export_to_file( "2013.com.canonical.plainbox::hexr", (), '/tmp') rc.para(_("Results saved to {0}").format(path)) def _send_results(self, rc, sa, secure_id, staging): rc.reset() rc.padding = (1, 1, 0, 1) rc.para(_("Sending hardware report to Canonical Certification")) rc.para(_("Server URL is: {0}").format(self.transport.url)) result = sa.export_to_transport( "2013.com.canonical.plainbox::hexr", self.transport) if 'url' in result: rc.para(result['url']) def _create_transport(self, sa, secure_id, staging): return sa.get_canonical_certification_transport( secure_id, staging=staging) def _collect_info(self, rc, sa): sa.select_providers('*') sa.start_new_session(_("Hardware Collection Session")) sa.select_test_plan(self.config.test_plan) sa.bootstrap() for job_id in sa.get_static_todo_list(): job = sa.get_job(job_id) builder = sa.run_job(job_id, 'silent', False) result = builder.get_result() sa.use_job_result(job_id, result) rc.para("- {0}: {1}".format(job.id, result)) if result.comments: rc.padding = (0, 0, 0, 2) rc.para("{0}".format(result.comments)) rc.reset() class SRUCommand(PlainBoxCommand): """ Command for running Stable Release Update (SRU) tests. Stable release updates are periodic fixes for nominated bugs that land in existing supported Ubuntu releases. To ensure a certain level of quality all SRU updates affecting hardware enablement are automatically tested on a pool of certified machines. """ gettext_domain = "checkbox-ng" def __init__(self, provider_loader, config_loader): self.provider_loader = provider_loader # This command does funky things to the command line parser and it # needs to load the config subsystem *early* so let's just load it now. self.config = config_loader() def invoked(self, ns): """Method called when the command is invoked.""" return sru(self.config).main(sys.argv[2:], exit=False) def register_parser(self, subparsers): """Method called to register command line arguments.""" parser = subparsers.add_parser( "sru", help=_("run automated stable release update tests")) parser.set_defaults(command=self) sru(self.config).register_arguments(parser) checkbox-ng-0.23/checkbox_ng/commands/__init__.py0000664000175000017500000000371512627266441022632 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands` -- shared code for checkbox-ng sub-commands ======================================================================= """ from plainbox.impl.clitools import CommandBase class CheckboxCommand(CommandBase): """ Simple interface class for checkbox-ng commands. Command objects like this are consumed by CheckBoxNGTool subclasses to implement hierarchical command system. The API supports arbitrary many sub commands in arbitrary nesting arrangement. """ gettext_domain = "checkbox-ng" def __init__(self, provider_loader, config_loader): """ Initialize a command with the specified arguments. :param provider_loader: A callable returning a list of Provider1 objects :param config_loader: A callable returning a Config object """ self._provider_loader = provider_loader self._config_loader = config_loader @property def provider_loader(self): """ a callable returning a list of PlainBox providers associated with this command """ return self._provider_loader @property def config_loader(self): """ a callable returning a Config object """ return self._config_loader checkbox-ng-0.23/checkbox_ng/commands/test_sru.py0000664000175000017500000000356012627266441022741 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ plainbox.impl.commands.test_sru =============================== Test definitions for plainbox.impl.box module """ from inspect import cleandoc from unittest import TestCase from plainbox.testing_utils.io import TestIO from checkbox_ng.main import main class TestSru(TestCase): def test_help(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['sru', '--help']) self.assertEqual(call.exception.args, (0,)) self.maxDiff = None expected = """ usage: checkbox sru [-h] --secure_id SECURE-ID [-T TEST-PLAN-ID] [--staging] [--check-config] optional arguments: -h, --help show this help message and exit --secure_id SECURE-ID Canonical hardware identifier -T TEST-PLAN-ID, --test-plan TEST-PLAN-ID load the specified test plan --staging Send the data to non-production test server --check-config run check-config before starting """ self.assertEqual(io.combined, cleandoc(expected) + "\n") checkbox-ng-0.23/checkbox_ng/commands/newcli.py0000664000175000017500000005526312627266441022361 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013-2014 Canonical Ltd. # Written by: # Sylvain Pineau # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands.cli` -- Command line sub-command =========================================================== .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from gettext import gettext as _ from logging import getLogger from shutil import copyfileobj import io import operator import os import re import sys from plainbox.abc import IJobResult from plainbox.impl.commands.inv_run import RunInvocation from plainbox.impl.exporter import ByteStringStreamTranslator from plainbox.impl.secure.config import Unset, ValidationError from plainbox.impl.secure.origin import CommandLineTextSource from plainbox.impl.secure.origin import Origin from plainbox.impl.secure.qualifiers import FieldQualifier from plainbox.impl.secure.qualifiers import OperatorMatcher from plainbox.impl.secure.qualifiers import RegExpJobQualifier from plainbox.impl.secure.qualifiers import select_jobs from plainbox.impl.session import SessionMetaData from plainbox.impl.session.jobs import InhibitionCause from plainbox.impl.transport import TransportError from plainbox.impl.transport import get_all_transports from plainbox.vendor.textland import get_display from checkbox_ng.misc import SelectableJobTreeNode from checkbox_ng.ui import ScrollableTreeNode from checkbox_ng.ui import ShowMenu from checkbox_ng.ui import ShowRerun from checkbox_ng.ui import ShowWelcome logger = getLogger("checkbox.ng.commands.newcli") class CliInvocation2(RunInvocation): """ Invocation of the 'checkbox cli' command. :ivar ns: The argparse namespace obtained from CliCommand :ivar _launcher: launcher specific to 'checkbox cli' :ivar _display: A textland display object :ivar _qualifier_list: A list of job qualifiers used to build the session desired_job_list """ def __init__(self, provider_loader, config_loader, ns, launcher, display=None): super().__init__(provider_loader, config_loader, ns, ns.color) if display is None: display = get_display() self._launcher = launcher self._display = display self._qualifier_list = [] self._testplan_list = [] self.select_qualifier_list() @property def launcher(self): """ TBD: 'checkbox cli' specific launcher settings """ return self._launcher @property def display(self): """ A TextLand display object """ return self._display def select_qualifier_list(self): # Add whitelists if 'whitelist' in self.ns and self.ns.whitelist: for whitelist_file in self.ns.whitelist: qualifier = self.get_whitelist_from_file( whitelist_file.name, whitelist_file) if qualifier is not None: self._qualifier_list.append(qualifier) # Add all the --include jobs for pattern in self.ns.include_pattern_list: origin = Origin(CommandLineTextSource('-i', pattern), None, None) try: qualifier = RegExpJobQualifier( '^{}$'.format(pattern), origin, inclusive=True) except Exception as exc: logger.warning( _("Incorrect pattern %r: %s"), pattern, exc) else: self._qualifier_list.append(qualifier) # Add all the --exclude jobs for pattern in self.ns.exclude_pattern_list: origin = Origin(CommandLineTextSource('-x', pattern), None, None) try: qualifier = RegExpJobQualifier( '^{}$'.format(pattern), origin, inclusive=False) except Exception as exc: logger.warning( _("Incorrect pattern %r: %s"), pattern, exc) else: self._qualifier_list.append(qualifier) if self.config.whitelist is not Unset: self._qualifier_list.append( self.get_whitelist_from_file(self.config.whitelist)) def select_testplan(self): # Add the test plan if self.ns.test_plan is not None: for provider in self.provider_list: for unit in provider.id_map[self.ns.test_plan]: if unit.Meta.name == 'test plan': self._qualifier_list.append(unit.get_qualifier()) self._testplan_list.append(unit) return else: logger.error(_("There is no test plan: %s"), self.ns.test_plan) def run(self): return self.do_normal_sequence() def do_normal_sequence(self): """ Proceed through normal set of steps that are required to runs jobs .. note:: This version is overridden as there is no better way to manage this pile rather than having a copy-paste + edits piece of text until arrowhead replaced plainbox run internals with a flow chart that can be derived meaningfully. For now just look for changes as compared to run.py's version. """ # Create transport early so that we can handle bugs before starting the # session. self.create_transport() if self.is_interactive: resumed = self.maybe_resume_session() else: self.create_manager(None) resumed = False # XXX: we don't want to know about new jobs just yet self.state.on_job_added.disconnect(self.on_job_added) # Create the job runner so that we can do stuff self.create_runner() # If we haven't resumed then do some one-time initialization if not resumed: # Show the welcome message self.show_welcome_screen() # Process testplan command line options self.select_testplan() # Maybe allow the user to do a manual whitelist selection if not self._qualifier_list: self.maybe_interactively_select_testplans() if self._testplan_list: self.manager.test_plans = tuple(self._testplan_list) # Store the application-identifying meta-data and checkpoint the # session. self.store_application_metadata() self.metadata.flags.add(SessionMetaData.FLAG_INCOMPLETE) self.manager.checkpoint() # Run all the local jobs. We need to do this to see all the things # the user may select if self.is_interactive: self.select_local_jobs() self.run_all_selected_jobs() self.interactively_pick_jobs_to_run() # Maybe ask the secure launcher to prompt for the password now. This is # imperfect as we are going to run local jobs and we cannot see if they # might need root or not. This cannot be fixed before template jobs are # added and local jobs deprecated and removed (at least not being a # part of the session we want to execute). self.maybe_warm_up_authentication() self.print_estimated_duration() self.run_all_selected_jobs() if self.is_interactive: while True: if self.maybe_rerun_jobs(): continue else: break self.export_and_send_results() if SessionMetaData.FLAG_INCOMPLETE in self.metadata.flags: print(self.C.header("Session Complete!", "GREEN")) self.metadata.flags.remove(SessionMetaData.FLAG_INCOMPLETE) self.manager.checkpoint() return 0 def store_application_metadata(self): super().store_application_metadata() self.metadata.app_blob = b'' def show_welcome_screen(self): text = self.launcher.text if self.is_interactive and text: self.display.run(ShowWelcome(text)) def maybe_interactively_select_testplans(self): if self.launcher.skip_whitelist_selection: self._qualifier_list.extend(self.get_default_testplans()) elif self.is_interactive: self._qualifier_list.extend( self.get_interactively_picked_testplans()) elif self.launcher.whitelist_selection: self._qualifier_list.extend(self.get_default_testplans()) logger.info(_("Selected testplans: %r"), self._qualifier_list) def get_interactively_picked_testplans(self): """ Show an interactive dialog that allows the user to pick a list of testplans. The set of testplans is limited to those offered by the 'default_providers' setting. :returns: A list of selected testplans """ testplans = [] testplan_selection = [] for provider in self.provider_list: testplans.extend( [unit for unit in provider.unit_list if unit.Meta.name == 'test plan' and re.search(self.launcher.whitelist_filter, unit.partial_id)]) testplan_name_list = [testplan.tr_name() for testplan in testplans] testplan_selection = [ testplans.index(t) for t in testplans if re.search(self.launcher.whitelist_selection, t.partial_id)] selected_list = self.display.run( ShowMenu(_("Suite selection"), testplan_name_list, testplan_selection)) if not selected_list: raise SystemExit(_("No testplan selected, aborting")) self._testplan_list.extend( [testplans[selected_index] for selected_index in selected_list]) return [testplans[selected_index].get_qualifier() for selected_index in selected_list] def get_default_testplans(self): testplans = [] for provider in self.provider_list: testplans.extend([ unit.get_qualifier() for unit in provider.unit_list if unit.Meta.name == 'test plan' and re.search( self.launcher.whitelist_selection, unit.partial_id)]) return testplans def create_transport(self): """ Create the ISessionStateTransport based on the command line options This sets the :ivar:`_transport`. """ # TODO: self._transport = None @property def expected_app_id(self): return 'checkbox' def select_local_jobs(self): print(self.C.header(_("Selecting Job Generators"))) # Create a qualifier list that will pick all local jobs out of the # subset of jobs also enumerated by the whitelists we've already # picked. # # Since each whitelist is a qualifier that selects jobs enumerated # within, we only need to and an exclusive qualifier that deselects # non-local jobs and we're done. qualifier_list = [] qualifier_list.extend(self._qualifier_list) origin = Origin.get_caller_origin() qualifier_list.append(FieldQualifier( 'plugin', OperatorMatcher(operator.ne, 'local'), origin, inclusive=False)) local_job_list = select_jobs( self.manager.state.job_list, qualifier_list) self._update_desired_job_list(local_job_list) def interactively_pick_jobs_to_run(self): print(self.C.header(_("Selecting Jobs For Execution"))) self._update_desired_job_list(select_jobs( self.manager.state.job_list, self._qualifier_list)) if self.launcher.skip_test_selection or not self.is_interactive: return tree = SelectableJobTreeNode.create_tree( self.manager.state, self.manager.state.run_list) title = _('Choose tests to run on your system:') self.display.run(ScrollableTreeNode(tree, title)) # NOTE: tree.selection is correct but ordered badly. To retain # the original ordering we should just treat it as a mask and # use it to filter jobs from desired_job_list. wanted_set = frozenset(tree.selection + tree.resource_jobs) job_list = [job for job in self.manager.state.run_list if job in wanted_set] self._update_desired_job_list(job_list) def export_and_send_results(self): if self.is_interactive: print(self.C.header(_("Results"))) exporter = self.manager.create_exporter( '2013.com.canonical.plainbox::text') exported_stream = io.BytesIO() exporter.dump_from_session_manager(self.manager, exported_stream) exported_stream.seek(0) # Need to rewind the file, puagh # This requires a bit more finesse, as exporters output bytes # and stdout needs a string. translating_stream = ByteStringStreamTranslator( sys.stdout, "utf-8") copyfileobj(exported_stream, translating_stream) # FIXME: this should probably not go to plainbox but checkbox-ng base_dir = os.path.join( os.getenv( 'XDG_DATA_HOME', os.path.expanduser("~/.local/share/")), "plainbox") if not os.path.exists(base_dir): os.makedirs(base_dir) exp_options = ['with-sys-info', 'with-summary', 'with-job-description', 'with-text-attachments', 'with-certification-status', 'with-job-defs', 'with-io-log', 'with-comments'] print() if self.launcher.exporter is not Unset: exporters = self.launcher.exporter else: exporters = [ '2013.com.canonical.plainbox::hexr', '2013.com.canonical.plainbox::html', '2013.com.canonical.plainbox::xlsx', '2013.com.canonical.plainbox::json', ] for unit_name in exporters: exporter = self.manager.create_exporter( unit_name, exp_options, strict=False) extension = exporter.unit.file_extension results_path = os.path.join( base_dir, 'submission.{}'.format(extension)) with open(results_path, "wb") as stream: exporter.dump_from_session_manager(self.manager, stream) print(_("View results") + " ({}): file://{}".format( extension, results_path)) self.submission_file = os.path.join(base_dir, 'submission.xml') if self.launcher.submit_to is not Unset: if self.launcher.submit_to == 'certification': # If we supplied a submit_url in the launcher, it # should override the one in the config. if self.launcher.submit_url: self.config.c3_url = self.launcher.submit_url # Same behavior for submit_to_hexr (a boolean flag which # should result in adding "submit_to_hexr=1" to transport # options later on) if self.launcher.submit_to_hexr: self.config.submit_to_hexr = True # for secure_id, config (which is user-writable) should # override launcher (which is not) if not self.config.secure_id: self.config.secure_id = self.launcher.secure_id # Override the secure_id configuration with the one provided # by the command-line option if self.ns.secure_id: self.config.secure_id = self.ns.secure_id if self.config.secure_id is Unset: again = True if not self.is_interactive: again = False while again: # TRANSLATORS: Do not translate the {} format marker. if self.ask_for_confirmation( _("\nSubmit results to {0}?".format( self.launcher.submit_url))): try: self.config.secure_id = input(_("Secure ID: ")) except ValidationError: print( _("ERROR: Secure ID must be 15 or " "18-character alphanumeric string")) else: again = False self.submit_certification_results() else: again = False else: # Automatically try to submit results if the secure_id is # valid self.submit_certification_results() elif self.launcher.submit_to == 'launchpad': if self.config.email_address is Unset: again = True if not self.is_interactive: again = False while again: if self.ask_for_confirmation( _("\nSubmit results to launchpad.net/+hwdb?")): self.config.email_address = input( _("Email address: ")) again = False self.submit_launchpad_results() else: again = False else: # Automatically try to submit results if the email_address # is valid self.submit_launchpad_results() def submit_launchpad_results(self): transport_cls = get_all_transports().get('launchpad') options_string = "field.emailaddress={}".format( self.config.email_address) transport = transport_cls(self.config.lp_url, options_string) # TRANSLATORS: Do not translate the {} format markers. print(_("Submitting results to {0} for email_address {1})").format( self.config.lp_url, self.config.email_address)) with open(self.submission_file, encoding='utf-8') as stream: try: # NOTE: don't pass the file-like object to this transport json = transport.send( stream.read(), self.config, session_state=self.manager.state) if json.get('url'): # TRANSLATORS: Do not translate the {} format marker. print(_("Submission uploaded to: {0}".format(json['url']))) elif json.get('status'): print(json['status']) else: # TRANSLATORS: Do not translate the {} format marker. print( _("Bad response from {0} transport".format(transport))) except TransportError as exc: print(str(exc)) def submit_certification_results(self): from checkbox_ng.certification import InvalidSecureIDError transport_cls = get_all_transports().get('certification') # TRANSLATORS: Do not translate the {} format markers. print(_("Submitting results to {0} for secure_id {1})").format( self.config.c3_url, self.config.secure_id)) option_chunks = [] option_chunks.append("secure_id={0}".format(self.config.secure_id)) if self.config.submit_to_hexr: option_chunks.append("submit_to_hexr=1") # Assemble the option string options_string = ",".join(option_chunks) # Create the transport object try: transport = transport_cls( self.config.c3_url, options_string) except InvalidSecureIDError as exc: print(exc) return False with open(self.submission_file) as stream: try: # Send the data, reading from the fallback file result = transport.send(stream, self.config) if 'url' in result: # TRANSLATORS: Do not translate the {} format marker. print(_("Successfully sent, submission status" " at {0}").format(result['url'])) else: # TRANSLATORS: Do not translate the {} format marker. print(_("Successfully sent, server response" ": {0}").format(result)) except TransportError as exc: print(str(exc)) def maybe_rerun_jobs(self): # create a list of jobs that qualify for rerunning rerun_candidates = [] for job in self.manager.state.run_list: job_state = self.manager.state.job_state_map[job.id] if job_state.result.outcome in ( IJobResult.OUTCOME_FAIL, IJobResult.OUTCOME_CRASH, IJobResult.OUTCOME_NOT_SUPPORTED): rerun_candidates.append(job) # bail-out early if no job qualifies for rerunning if not rerun_candidates: return False tree = SelectableJobTreeNode.create_tree( self.manager.state, rerun_candidates) # nothing to select in root node and categories - bailing out if not tree.jobs and not tree._categories: return False # deselect all by default tree.set_descendants_state(False) self.display.run(ShowRerun(tree, _("Select jobs to re-run"))) wanted_set = frozenset(tree.selection) if not wanted_set: # nothing selected - nothing to run return False # include resource jobs that selected jobs depend on resources_to_rerun = [] for job in wanted_set: job_state = self.manager.state.job_state_map[job.id] for inhibitor in job_state.readiness_inhibitor_list: if inhibitor.cause == InhibitionCause.FAILED_DEP: resources_to_rerun.append(inhibitor.related_job) # reset outcome of jobs that are selected for re-running for job in list(wanted_set) + resources_to_rerun: from plainbox.impl.result import MemoryJobResult self.manager.state.job_state_map[job.id].result = \ MemoryJobResult({}) self.run_all_selected_jobs() return True checkbox-ng-0.23/checkbox_ng/commands/submit.py0000664000175000017500000001342212627266441022372 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Sylvain Pineau # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.commands.submit` -- the submit sub-command ============================================================ .. warning:: THIS MODULE DOES NOT HAVE STABLE PUBLIC API """ from argparse import ArgumentTypeError from plainbox.i18n import docstring from plainbox.i18n import gettext as _ from plainbox.i18n import gettext_noop as N_ import re from plainbox.impl.commands import PlainBoxCommand from plainbox.impl.secure.config import Unset from plainbox.impl.transport import TransportError from checkbox_ng.certification import CertificationTransport from checkbox_ng.config import SECURE_ID_PATTERN class SubmitInvocation: """ Helper class instantiated to perform a particular invocation of the submit command. Unlike the SRU command itself, this class is instantiated each time. """ def __init__(self, ns): self.ns = ns def run(self): options_string = "secure_id={0}".format(self.ns.secure_id) transport = CertificationTransport(self.ns.url, options_string) try: with open(self.ns.submission, "r", encoding='utf-8') as subm_file: result = transport.send(subm_file) except (TransportError, OSError) as exc: raise SystemExit(exc) else: if 'url' in result: # TRANSLATORS: Do not translate the {} format marker. print(_("Successfully sent, submission status" " at {0}").format(result['url'])) else: # TRANSLATORS: Do not translate the {} format marker. print(_("Successfully sent, server response" ": {0}").format(result)) @docstring( # TRANSLATORS: please leave various options (both long and short forms), # environment variables and paths in their original form. Also keep the # special @EPILOG@ string. The first line of the translation is special and # is used as the help message. Please keep the pseudo-statement form and # don't finish the sentence with a dot. Pay extra attention to whitespace. # It must be correctly preserved or the result won't work. In particular # the leading whitespace *must* be preserved and *must* have the same # length on each line. N_(""" submit test results to the Canonical certification website This command sends the XML results file to the Certification website. """)) class SubmitCommand(PlainBoxCommand): gettext_domain = "checkbox-ng" def __init__(self, config_loader): self.config = config_loader() def invoked(self, ns): return SubmitInvocation(ns).run() def register_parser(self, subparsers): parser = subparsers.add_parser("submit", help=_( "submit test results to the Canonical certification website")) self.register_arguments(parser) def register_arguments(self, parser): parser.set_defaults(command=self) parser.add_argument( 'submission', help=_("The path to the results xml file")) self.register_optional_arguments(parser, required=True) def register_optional_arguments(self, parser, required=False): if self.config.secure_id is not Unset: parser.set_defaults(secure_id=self.config.secure_id) def secureid(secure_id): if not re.match(SECURE_ID_PATTERN, secure_id): raise ArgumentTypeError( _("must be 15 or 18-character alphanumeric string")) return secure_id required_check = False if required: required_check = self.config.secure_id is Unset parser.add_argument( '--secure_id', metavar=_("SECURE-ID"), required=required_check, type=secureid, help=_("associate submission with a machine using this SECURE-ID")) # Interpret this setting here # Please remember the Unset.__bool__() return False # After Interpret the setting, # self.config.submit_to_c3 should has value or be Unset. try: if (self.config.submit_to_c3 and (self.config.submit_to_c3.lower() in ('yes', 'true') or int(self.config.submit_to_c3) == 1)): # self.config.c3_url has a default value written in config.py parser.set_defaults(url=self.config.c3_url) else: # if submit_to_c3 is castable to int but not 1 # this is still set as Unset # otherwise url requirement will be None self.config.submit_to_c3 = Unset except ValueError: # When submit_to_c3 is something other than 'yes', 'true', # castable to integer, it raises ValueError. # e.g. 'no', 'false', 'asdf' ...etc. # In this case, it is still set as Unset. self.config.submit_to_c3 = Unset required_check = False if required: required_check = self.config.submit_to_c3 is Unset parser.add_argument( '--url', metavar=_("URL"), required=required_check, help=_("destination to submit to")) checkbox-ng-0.23/checkbox_ng/test_config.py0000664000175000017500000000260712627266441021575 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2013 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ checkbox_ng.test_config ======================= Test definitions for checkbox_ng.config module """ from unittest import TestCase from plainbox.impl.secure.config import Unset from checkbox_ng.config import CheckBoxConfig class PlainBoxConfigTests(TestCase): def test_smoke(self): config = CheckBoxConfig() self.assertIs(config.secure_id, Unset) secure_id = "0123456789ABCDE" config.secure_id = secure_id self.assertEqual(config.secure_id, secure_id) with self.assertRaises(ValueError): config.secure_id = "bork" self.assertEqual(config.secure_id, secure_id) del config.secure_id self.assertIs(config.secure_id, Unset) checkbox-ng-0.23/checkbox_ng/test_main.py0000664000175000017500000000711712627266441021255 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2012-2014 Canonical Ltd. # Written by: # Zygmunt Krynicki # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ checkbox_ng.test_main ===================== Test definitions for checkbox_ng.main module """ from inspect import cleandoc from unittest import TestCase from plainbox.impl.clitools import ToolBase from plainbox.testing_utils.io import TestIO from checkbox_ng import __version__ as version from checkbox_ng.main import main class TestMain(TestCase): def test_version(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['--version']) self.assertEqual(call.exception.args, (0,)) self.assertEqual(io.combined, "{}\n".format( ToolBase.format_version_tuple(version))) def test_help(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main(['--help']) self.assertEqual(call.exception.args, (0,)) self.maxDiff = None expected = """ usage: checkbox [-h] [--version] [-v] [-D] [-C] [-T LOGGER] [-P] [-I] {sru,check-config,submit,launcher,self-test} ... positional arguments: {sru,check-config,submit,launcher,self-test} sru run automated stable release update tests check-config check and display plainbox configuration submit submit test results to the Canonical certification website launcher run a customized testing session self-test run unit and integration tests optional arguments: -h, --help show this help message and exit --version show program's version number and exit logging and debugging: -v, --verbose be more verbose (same as --log-level=INFO) -D, --debug enable DEBUG messages on the root logger -C, --debug-console display DEBUG messages in the console -T LOGGER, --trace LOGGER enable DEBUG messages on the specified logger (can be used multiple times) -P, --pdb jump into pdb (python debugger) when a command crashes -I, --debug-interrupt crash on SIGINT/KeyboardInterrupt, useful with --pdb """ self.assertEqual(io.combined, cleandoc(expected) + "\n") def test_run_without_args(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: main([]) self.assertEqual(call.exception.args, (2,)) expected = """ usage: checkbox [-h] [--version] [-v] [-D] [-C] [-T LOGGER] [-P] [-I] {sru,check-config,submit,launcher,self-test} ... checkbox: error: too few arguments """ self.assertEqual(io.combined, cleandoc(expected) + "\n") checkbox-ng-0.23/checkbox_ng/launchpad.py0000664000175000017500000002071312627266441021226 0ustar pierrepierre00000000000000# This file is part of Checkbox. # # Copyright 2014 Canonical Ltd. # Written by: # Brendan Donegan # # Checkbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, # as published by the Free Software Foundation. # # Checkbox is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Checkbox. If not, see . """ :mod:`checkbox_ng.launchpad` -- plainbox transport to Launchpad database ============================================================================= This module contains a PlainBox transport that knows how to send the submission XML data to the Launchpad hardware database. """ from datetime import datetime from gettext import gettext as _ from io import BytesIO from logging import getLogger from socket import gethostname import bz2 import hashlib import requests from checkbox_support.lib.dmi import Dmi from plainbox.impl.secure.config import Unset from plainbox.impl.transport import TransportBase, TransportError logger = getLogger("checkbox.ng.launchpad") class InvalidSubmissionDataError(TransportError): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class LaunchpadTransport(TransportBase): """ Transport for sending data to Launchpad database. - POSTs data to a http(s) endpoint - Adds a header with a hardware identifier - Data is expected to be in checkbox xml-compatible format. This means it will work best with a stream produced by the xml exporter. """ def _get_resource_attr(self, session_state, resource, attr): resource_result = session_state.resource_map.get(resource) if not resource_result: raise InvalidSubmissionDataError( _("Cannot get {0} resource job").format(resource)) attr_value = getattr(resource_result[0], attr) if attr_value is None: raise InvalidSubmissionDataError( _("{0} has no attribute {1}").format(resource, attr)) return attr_value def _get_launchpad_form_fields(self, session_state): form_fields = {} form_fields['field.private'] = 'False' form_fields['field.contactable'] = 'False' form_fields['field.live_cd'] = 'False' form_fields['field.format'] = 'VERSION_1' form_fields['field.actions.upload'] = 'Upload' form_fields['field.date_created'] = datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%S") arch = self._get_resource_attr( session_state, '2013.com.canonical.certification::dpkg', 'architecture') form_fields['field.architecture'] = arch distro = self._get_resource_attr( session_state, '2013.com.canonical.certification::lsb', 'distributor_id') form_fields['field.distribution'] = distro series = self._get_resource_attr( session_state, '2013.com.canonical.certification::lsb', 'codename') form_fields['field.distroseries'] = series dmi_resources = session_state.resource_map.get( '2013.com.canonical.certification::dmi') if dmi_resources is None: raise InvalidSubmissionDataError( _("DMI resources not found")) system_id = "" for resource in dmi_resources: if resource.category == 'CHASSIS': chassis_type = Dmi.chassis_name_to_type[resource.product] vendor = getattr(resource, 'vendor', "") model = getattr(resource, 'model', "") fingerprint = hashlib.md5() for field in ["Computer", "unknown", chassis_type, vendor, model]: fingerprint.update(field.encode('utf-8')) system_id = fingerprint.hexdigest() if not system_id: raise InvalidSubmissionDataError(_("System ID not found")) form_fields['field.system'] = system_id fingerprint = hashlib.md5() fingerprint.update(system_id.encode('utf-8')) fingerprint.update(str(datetime.utcnow()).encode('utf-8')) form_fields['field.submission_key'] = fingerprint.hexdigest() return form_fields def send(self, data, config=None, session_state=None): """ Sends data to the specified server. :param data: Data containing the xml dump to be sent to the server. This can be either bytes or a file-like object (BytesIO works fine too). If this is a file-like object, it will be read and streamed "on the fly". :param config: An optional PlainBoxConfig object. If http_proxy and https_proxy values are set in this config object, they will be used to send data via the specified protocols. Note that the transport also honors the http_proxy and https_proxy environment variables. Proxy string format is http://[user:password@]:port :param session_state: ? :returns: A dictionary with responses from the server if submission was successful and empty dictionary otherwise. :raises ValueError: If no session state was provided. :raises TransportError: - If sending timed out. - If connection failed outright. - If the server returned a non-success result code - If a required resource job is missing from the submission or a resource job is missing a required attribute. The following resource/attribute pairs are needed: - dpkg: architecture - lsb: distributor_id - lsb: codename - dmi: product """ proxies = None if config and config.environment is not Unset: proxies = { proto[:-len("_proxy")]: config.environment[proto] for proto in ['http_proxy', 'https_proxy'] if proto in config.environment } if session_state is None: raise ValueError("LaunchpadTransport requires a session " "state to be provided.") logger.debug("Sending to %s, email is %s", self.url, self.options['field.emailaddress']) lp_headers = {"x-launchpad-hwdb-submission": ""} form_fields = self._get_launchpad_form_fields(session_state) form_fields['field.emailaddress'] = self.options['field.emailaddress'] compressed_payload = bz2.compress(data.encode('utf-8')) file = BytesIO(compressed_payload) file.name = "{}.xml.bz2".format(gethostname()) file.size = len(compressed_payload) submission_data = {'field.submission_data': file} try: response = requests.post(self.url, data=form_fields, files=submission_data, headers=lp_headers, proxies=proxies) except requests.exceptions.Timeout as exc: raise TransportError( _("Request to {0} timed out: {1}").format(self.url, exc)) except requests.exceptions.InvalidSchema as exc: raise TransportError( _("Invalid destination URL: {0}").format(exc)) except requests.exceptions.ConnectionError as exc: raise TransportError( _("Unable to connect to {0}: {1}").format(self.url, exc)) if response is not None: try: # This will raise HTTPError for status != 20x response.raise_for_status() except requests.exceptions.RequestException as exc: raise TransportError(str(exc)) logger.debug(_("Success! Server said %s"), response.text) status = _('The submission was uploaded to Launchpad successfully') if (response.headers['x-launchpad-hwdb-submission'] != ( 'OK data stored')): status = response.headers['x-launchpad-hwdb-submission'] return {'status': status} # ISessionStateTransport.send must return dictionary return {} checkbox-ng-0.23/PKG-INFO0000664000175000017500000000141412633675304015534 0ustar pierrepierre00000000000000Metadata-Version: 1.0 Name: checkbox-ng Version: 0.23 Summary: Checkbox - Command Line Test Runner Home-page: https://launchpad.net/checkbox-ng/ Author: Zygmunt Krynicki Author-email: zygmunt.krynicki@canonical.com License: GPLv3 Description: CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ CheckBoxNG is pre-installed on Ubuntu 14.04. It is also available in Debian (as checkbox-ng) Testing. Platform: UNKNOWN checkbox-ng-0.23/checkbox_ng.egg-info/0000775000175000017500000000000012633675304020403 5ustar pierrepierre00000000000000checkbox-ng-0.23/checkbox_ng.egg-info/requires.txt0000664000175000017500000000011212633675304022775 0ustar pierrepierre00000000000000checkbox-support >= 0.2 guacamole >= 0.9 plainbox >= 0.5.3 requests >= 1.0checkbox-ng-0.23/checkbox_ng.egg-info/PKG-INFO0000664000175000017500000000141412633675304021500 0ustar pierrepierre00000000000000Metadata-Version: 1.0 Name: checkbox-ng Version: 0.23 Summary: Checkbox - Command Line Test Runner Home-page: https://launchpad.net/checkbox-ng/ Author: Zygmunt Krynicki Author-email: zygmunt.krynicki@canonical.com License: GPLv3 Description: CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ CheckBoxNG is pre-installed on Ubuntu 14.04. It is also available in Debian (as checkbox-ng) Testing. Platform: UNKNOWN checkbox-ng-0.23/checkbox_ng.egg-info/SOURCES.txt0000664000175000017500000000225312633675304022271 0ustar pierrepierre00000000000000COPYING MANIFEST.in README.rst setup.cfg setup.py checkbox_ng/__init__.py checkbox_ng/certification.py checkbox_ng/config.py checkbox_ng/launcher.py checkbox_ng/launchpad.py checkbox_ng/main.py checkbox_ng/misc.py checkbox_ng/test_certification.py checkbox_ng/test_config.py checkbox_ng/test_main.py checkbox_ng/test_misc.py checkbox_ng/tests.py checkbox_ng/tools.py checkbox_ng/ui.py checkbox_ng.egg-info/PKG-INFO checkbox_ng.egg-info/SOURCES.txt checkbox_ng.egg-info/dependency_links.txt checkbox_ng.egg-info/entry_points.txt checkbox_ng.egg-info/requires.txt checkbox_ng.egg-info/top_level.txt checkbox_ng/commands/__init__.py checkbox_ng/commands/cli.py checkbox_ng/commands/launcher.py checkbox_ng/commands/newcli.py checkbox_ng/commands/sru.py checkbox_ng/commands/submit.py checkbox_ng/commands/test_sru.py contrib/checkbox-ci-installed-notifier.service contrib/checkbox-ci-mailer.service contrib/checkbox-sru.service contrib/com.canonical.certification.PlainBox1.service docs/bugs.rst docs/changelog.rst docs/conf.py docs/index.rst docs/launcher-tutorial.rst docs/profiles.rst docs/release.rst docs/stack.rst docs/scripts/brightness_test.rst docs/scripts/index.rst launchers/checkbox-clicheckbox-ng-0.23/checkbox_ng.egg-info/dependency_links.txt0000664000175000017500000000000112633675304024451 0ustar pierrepierre00000000000000 checkbox-ng-0.23/checkbox_ng.egg-info/top_level.txt0000664000175000017500000000001412633675304023130 0ustar pierrepierre00000000000000checkbox_ng checkbox-ng-0.23/checkbox_ng.egg-info/entry_points.txt0000664000175000017500000000043012633675304023676 0ustar pierrepierre00000000000000[console_scripts] checkbox = checkbox_ng.main:main checkbox-submit = checkbox_ng.main:submit checkbox-launcher = checkbox_ng.main:launcher [plainbox.transport] launchpad = checkbox_ng.launchpad:LaunchpadTransport certification = checkbox_ng.certification:CertificationTransport checkbox-ng-0.23/README.rst0000664000175000017500000000062612627266441016133 0ustar pierrepierre00000000000000CheckBoxNG ========== :term:`CheckBoxNG` is a hardware testing tool useful for certifying laptops, desktops and servers with Ubuntu. It is a new version of :term:`CheckBox` that is built directly on top of :term:`PlainBox` CheckBoxNG *replaces* CheckBox, where applicable. Installation ============ CheckBoxNG is pre-installed on Ubuntu 14.04. It is also available in Debian (as checkbox-ng) Testing. checkbox-ng-0.23/COPYING0000664000175000017500000010451312627266441015477 0ustar pierrepierre00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . checkbox-ng-0.23/launchers/0000775000175000017500000000000012633675304016423 5ustar pierrepierre00000000000000checkbox-ng-0.23/launchers/checkbox-cli0000775000175000017500000000110612627266441020703 0ustar pierrepierre00000000000000#!/usr/bin/env checkbox-launcher [welcome] text = Welcome to System Testing! Checkbox provides tests to confirm that your system is working properly. Once you are finished running the tests, you can view a summary report for your system and submit your results to Launchpad. Warning: Some tests could cause your system to freeze or become unresponsive. Please save all your work and close all other running applications before beginning the testing process. [suite] whitelist_filter = ^.*$ whitelist_selection = ^default$ [transport] submit_to = launchpad checkbox-ng-0.23/MANIFEST.in0000664000175000017500000000017012627266441016174 0ustar pierrepierre00000000000000include README.md include COPYING recursive-include contrib *.service recursive-include docs *.rst include docs/conf.py checkbox-ng-0.23/setup.cfg0000664000175000017500000000017712633675304016265 0ustar pierrepierre00000000000000[upload] sign = True [upload_docs] upload-dir = build/sphinx/html [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0