mirror of
https://git.yoctoproject.org/poky
synced 2026-04-13 14:02:21 +02:00
bitbake: toaster/contrib: adding TTS squashed patch
In order to move the Toaster Test System in Toaster itself, we create a contrib directory. The TTS is added as a squashed patch with no history. It contains code contributed by Ke Zou <ke.zou@windriver.com>. (Bitbake rev: 7d24fea2b5dcaac6add738b6fb4700d698824286) Signed-off-by: Alexandru DAMIAN <alexandru.damian@intel.com> Signed-off-by: Richard Purdie <richard.purdie@linuxfoundation.org>
This commit is contained in:
committed by
Richard Purdie
parent
23f5b009e0
commit
80ca4f00f8
6
bitbake/lib/toaster/contrib/README
Normal file
6
bitbake/lib/toaster/contrib/README
Normal file
@@ -0,0 +1,6 @@
|
||||
contrib directory for toaster
|
||||
|
||||
This directory holds code that works with Toaster, without being an integral part of the Toaster project.
|
||||
It is intended for testing code, testing fixtures, tools for Toaster, etc.
|
||||
|
||||
NOTE: This directory is NOT a Python module.
|
||||
41
bitbake/lib/toaster/contrib/tts/README
Normal file
41
bitbake/lib/toaster/contrib/tts/README
Normal file
@@ -0,0 +1,41 @@
|
||||
|
||||
Toaster Testing Framework
|
||||
Yocto Project
|
||||
|
||||
|
||||
Rationale
|
||||
------------
|
||||
As Toaster contributions grow with the number of people that contribute code, verifying each patch prior to submitting upstream becomes a hard-to-scale problem for humans. We devised this system in order to run patch-level validation, trying to eliminate common problems from submitted patches, in an automated fashion.
|
||||
|
||||
The Toaster Testing Framework is a set of Python scripts that provides an extensible way to write smoke and regression tests that will be run on each patch set sent for review on the toaster mailing list.
|
||||
|
||||
|
||||
Usage
|
||||
------------
|
||||
There are three main executable scripts in this directory.
|
||||
* runner.py is designed to be run from the command line. It requires, as mandatory parameter, a branch name on poky-contrib, branch which contains the patches to be tested. The program will auto-discover the available tests residing in this directory by looking for unittest classes, and will run the tests on the branch dumping the output to the standard output. Optionally, it can take parameters inhibiting the branch checkout, or specifying a single test to be run, for debugging purposes.
|
||||
* launcher.py is a designed to be run from a crontab or similar scheduling mechanism. It looks up a backlog file containing branches-to-test (named tasks in the source code), select the first one in FIFO manner, and launch runner.py on it. It will await for completion, and email the standard output and standard error dumps from the runner.py execution
|
||||
* recv.py is an email receiver, designed to be called as a pipe from a .forward file. It is used to monitor a mailing list, for example, and add tasks to the backlog based on review requests coming on the mailing list.
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
As prerequisite, we expect a functioning email system on a machine with Python2.
|
||||
|
||||
The broad steps to installation
|
||||
* set up the .forward on the receiving email account to pipe to the recv.py file
|
||||
* edit config.py and settings.json to alter for local installation settings
|
||||
* on email receive, verify backlog.txt to see that the tasks are received and marked for processing
|
||||
* execute launcher.py in command line to verify that a test occurs with no problems, and that the outgoing email is delivered
|
||||
* add launcher.py
|
||||
|
||||
|
||||
|
||||
Contribute
|
||||
------------
|
||||
What we need are tests. Add your own tests to either tests.py file, or to a new file.
|
||||
Use "config.logger" to write logs that will make it to email.
|
||||
|
||||
Commonly used code should be going to shellutils, and configuration to config.py.
|
||||
|
||||
Contribute code by emailing patches to the list: toaster@yoctoproject.org (membership required)
|
||||
9
bitbake/lib/toaster/contrib/tts/TODO
Normal file
9
bitbake/lib/toaster/contrib/tts/TODO
Normal file
@@ -0,0 +1,9 @@
|
||||
We need to implement tests:
|
||||
|
||||
automated link checker; currently
|
||||
$ linkchecker -t 1000 -F csv http://localhost:8000/
|
||||
|
||||
integrate the w3c-validation service; currently
|
||||
$ python urlcheck.py
|
||||
|
||||
|
||||
2
bitbake/lib/toaster/contrib/tts/backlog.txt
Normal file
2
bitbake/lib/toaster/contrib/tts/backlog.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
michaelw/toaster-frontend-cleanups|PENDING
|
||||
adamian/test_0|PENDING
|
||||
70
bitbake/lib/toaster/contrib/tts/config.py
Normal file
70
bitbake/lib/toaster/contrib/tts/config.py
Normal file
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
# This is the configuration/single module for tts
|
||||
# everything that would be a global variable goes here
|
||||
|
||||
import os, sys, logging
|
||||
|
||||
LOGDIR = "log"
|
||||
SETTINGS_FILE = os.path.join(os.path.dirname(__file__), "settings.json")
|
||||
TEST_DIR_NAME = "tts_testdir"
|
||||
|
||||
OWN_PID = os.getpid()
|
||||
|
||||
OWN_EMAIL_ADDRESS = "Toaster Testing Framework <alexandru.damian@intel.com>"
|
||||
REPORT_EMAIL_ADDRESS = "alexandru.damian@intel.com"
|
||||
|
||||
# make sure we have the basic logging infrastructure
|
||||
logger = logging.getLogger("toastertest")
|
||||
__console = logging.StreamHandler(sys.stdout)
|
||||
__console.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s"))
|
||||
logger.addHandler(__console)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
# singleton file names
|
||||
LOCKFILE="/tmp/ttf.lock"
|
||||
BACKLOGFILE=os.path.join(os.path.dirname(__file__), "backlog.txt")
|
||||
|
||||
# task states
|
||||
def enum(*sequential, **named):
|
||||
enums = dict(zip(sequential, range(len(sequential))), **named)
|
||||
reverse = dict((value, key) for key, value in enums.iteritems())
|
||||
enums['reverse_mapping'] = reverse
|
||||
return type('Enum', (), enums)
|
||||
|
||||
|
||||
class TASKS:
|
||||
PENDING = "PENDING"
|
||||
INPROGRESS = "INPROGRESS"
|
||||
DONE = "DONE"
|
||||
|
||||
@staticmethod
|
||||
def next_task(task):
|
||||
if task == TASKS.PENDING:
|
||||
return TASKS.INPROGRESS
|
||||
if task == TASKS.INPROGRESS:
|
||||
return TASKS.DONE
|
||||
raise Exception("Invalid next task state for %s" % task)
|
||||
|
||||
# TTS specific
|
||||
CONTRIB_REPO = "git@git.yoctoproject.org:poky-contrib"
|
||||
|
||||
100
bitbake/lib/toaster/contrib/tts/launcher.py
Executable file
100
bitbake/lib/toaster/contrib/tts/launcher.py
Executable file
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
# Program to run the next task listed from the backlog.txt; designed to be
|
||||
# run from crontab.
|
||||
|
||||
from __future__ import print_function
|
||||
import sys, os, config, shellutils
|
||||
from shellutils import ShellCmdException
|
||||
|
||||
# Import smtplib for the actual sending function
|
||||
import smtplib
|
||||
|
||||
# Import the email modules we'll need
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
DEBUG=True
|
||||
|
||||
def _take_lockfile():
|
||||
return shellutils.lockfile(shellutils.mk_lock_filename())
|
||||
|
||||
|
||||
def read_next_task_by_state(task_state, task_name = None):
|
||||
if not os.path.exists(os.path.join(os.path.dirname(__file__), config.BACKLOGFILE)):
|
||||
return None
|
||||
os.rename(config.BACKLOGFILE, config.BACKLOGFILE + ".tmp")
|
||||
task = None
|
||||
with open(config.BACKLOGFILE + ".tmp", "r") as f_in:
|
||||
with open(config.BACKLOGFILE, "w") as f_out:
|
||||
for line in f_in.readlines():
|
||||
if task is None:
|
||||
fields = line.strip().split("|", 2)
|
||||
if fields[1] == task_state:
|
||||
if task_name is None or task_name == fields[0]:
|
||||
task = fields[0]
|
||||
print("Updating %s %s to %s" % (task, task_state, config.TASKS.next_task(task_state)))
|
||||
line = "%s|%s\n" % (task, config.TASKS.next_task(task_state))
|
||||
f_out.write(line)
|
||||
os.remove(config.BACKLOGFILE + ".tmp")
|
||||
return task
|
||||
|
||||
def send_report(task_name, plaintext, errtext = None):
|
||||
if errtext is None:
|
||||
msg = MIMEText(plaintext)
|
||||
else:
|
||||
if plaintext is None:
|
||||
plaintext=""
|
||||
msg = MIMEText("--STDOUT dump--\n\n%s\n\n--STDERR dump--\n\n%s" % (plaintext, errtext))
|
||||
|
||||
msg['Subject'] = "[review-request] %s - smoke test results" % task_name
|
||||
msg['From'] = config.OWN_EMAIL_ADDRESS
|
||||
msg['To'] = config.REPORT_EMAIL_ADDRESS
|
||||
|
||||
s = smtplib.SMTP("localhost")
|
||||
s.sendmail(config.OWN_EMAIL_ADDRESS, [config.REPORT_EMAIL_ADDRESS], msg.as_string())
|
||||
s.quit()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# we don't do anything if we have another instance of us running
|
||||
lf = _take_lockfile()
|
||||
|
||||
if lf is None:
|
||||
if DEBUG:
|
||||
print("Concurrent script in progress, exiting")
|
||||
sys.exit(1)
|
||||
|
||||
next_task = read_next_task_by_state(config.TASKS.PENDING)
|
||||
if next_task is not None:
|
||||
print("Next task is", next_task)
|
||||
errtext = None
|
||||
out = None
|
||||
try:
|
||||
out = shellutils.run_shell_cmd("./runner.py %s" % next_task)
|
||||
pass
|
||||
except ShellCmdException as e:
|
||||
print("Failed while running the test runner: %s", e)
|
||||
errtext = e.__str__()
|
||||
send_report(next_task, out, errtext)
|
||||
read_next_task_by_state(config.TASKS.INPROGRESS, next_task)
|
||||
else:
|
||||
print("No task")
|
||||
|
||||
shellutils.unlockfile(lf)
|
||||
0
bitbake/lib/toaster/contrib/tts/log/.create
Normal file
0
bitbake/lib/toaster/contrib/tts/log/.create
Normal file
51
bitbake/lib/toaster/contrib/tts/recv.py
Executable file
51
bitbake/lib/toaster/contrib/tts/recv.py
Executable file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
# Program to receive review requests by email and log tasks to backlog.txt
|
||||
# Designed to be run by the email system from a .forward file:
|
||||
#
|
||||
# cat .forward
|
||||
# |[full/path]/recv.py
|
||||
|
||||
from __future__ import print_function
|
||||
import sys, os, config, shellutils
|
||||
from shellutils import ShellCmdException
|
||||
|
||||
from email.parser import Parser
|
||||
|
||||
def recv_mail(datastring):
|
||||
headers = Parser().parsestr(datastring)
|
||||
return headers['subject']
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
lf = shellutils.lockfile(shellutils.mk_lock_filename(), retry = True)
|
||||
|
||||
subject = recv_mail(sys.stdin.read())
|
||||
|
||||
subject_parts = subject.split()
|
||||
if "[review-request]" in subject_parts:
|
||||
task_name = subject_parts[subject_parts.index("[review-request]") + 1]
|
||||
with open(os.path.join(os.path.dirname(__file__), config.BACKLOGFILE), "a") as fout:
|
||||
line = "%s|%s\n" % (task_name, config.TASKS.PENDING)
|
||||
fout.write(line)
|
||||
|
||||
shellutils.unlockfile(lf)
|
||||
|
||||
200
bitbake/lib/toaster/contrib/tts/runner.py
Executable file
200
bitbake/lib/toaster/contrib/tts/runner.py
Executable file
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
|
||||
# This is the main test execution controller. It is designed to be run
|
||||
# manually from the command line, or to be called from a different program
|
||||
# that schedules test execution.
|
||||
#
|
||||
# Execute runner.py -h for help.
|
||||
|
||||
|
||||
|
||||
from __future__ import print_function
|
||||
import optparse
|
||||
import sys, os
|
||||
import unittest, inspect, importlib
|
||||
import logging, pprint, json
|
||||
|
||||
from shellutils import *
|
||||
|
||||
import config
|
||||
|
||||
# we also log to a file, in addition to console, because our output is important
|
||||
__log_file_name =os.path.join(os.path.dirname(__file__),"log/tts_%d.log" % config.OWN_PID)
|
||||
mkdirhier(os.path.dirname(__log_file_name))
|
||||
__log_file = open(__log_file_name, "w")
|
||||
__file_handler = logging.StreamHandler(__log_file)
|
||||
__file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s"))
|
||||
|
||||
config.logger.addHandler(__file_handler)
|
||||
|
||||
|
||||
# set up log directory
|
||||
try:
|
||||
if not os.path.exists(config.LOGDIR):
|
||||
os.mkdir(config.LOGDIR)
|
||||
else:
|
||||
if not os.path.isdir(config.LOGDIR):
|
||||
raise Exception("Expected log dir '%s' is not actually a directory." % config.LOGDIR)
|
||||
except OSError as e:
|
||||
raise e
|
||||
|
||||
# creates the under-test-branch as a separate directory
|
||||
def set_up_test_branch(settings, branch_name):
|
||||
testdir = "%s/%s.%d" % (settings['workdir'], config.TEST_DIR_NAME, config.OWN_PID)
|
||||
|
||||
# creates the host dir
|
||||
if os.path.exists(testdir):
|
||||
raise Exception("Test dir '%s'is already there, aborting" % testdir)
|
||||
os.mkdir(testdir)
|
||||
|
||||
# copies over the .git from the localclone
|
||||
run_shell_cmd("cp -a '%s'/.git '%s'" % (settings['localclone'], testdir))
|
||||
|
||||
# add the remote if it doesn't exist
|
||||
crt_remotes = run_shell_cmd("git remote -v", cwd = testdir)
|
||||
remotes = [word for line in crt_remotes.split("\n") for word in line.split()]
|
||||
if not config.CONTRIB_REPO in remotes:
|
||||
remote_name = "tts_contrib"
|
||||
run_shell_cmd("git remote add %s %s" % (remote_name, config.CONTRIB_REPO), cwd = testdir)
|
||||
else:
|
||||
remote_name = remotes[remotes.index(config.CONTRIB_REPO) - 1]
|
||||
|
||||
# do the fetch
|
||||
run_shell_cmd("git fetch %s -p" % remote_name, cwd=testdir)
|
||||
|
||||
# do the checkout
|
||||
run_shell_cmd("git checkout origin/master && git branch -D %s; git checkout %s/%s -b %s && git reset --hard" % (branch_name,remote_name,branch_name,branch_name), cwd=testdir)
|
||||
|
||||
return testdir
|
||||
|
||||
|
||||
def __search_for_tests():
|
||||
# we find all classes that can run, and run them
|
||||
tests = []
|
||||
for dir_name, dirs_list, files_list in os.walk(os.path.dirname(os.path.abspath(__file__))):
|
||||
for f in [f[:-3] for f in files_list if f.endswith(".py") and not f.startswith("__init__")]:
|
||||
config.logger.debug("Inspecting module %s", f)
|
||||
current_module = importlib.import_module(f)
|
||||
crtclass_names = vars(current_module)
|
||||
for v in crtclass_names:
|
||||
t = crtclass_names[v]
|
||||
if isinstance(t, type(unittest.TestCase)) and issubclass(t, unittest.TestCase):
|
||||
tests.append((f,v))
|
||||
break
|
||||
return tests
|
||||
|
||||
|
||||
# boilerplate to self discover tests and run them
|
||||
def execute_tests(dir_under_test, testname):
|
||||
|
||||
if testname is not None and "." in testname:
|
||||
tests = []
|
||||
tests.append(tuple(testname.split(".", 2)))
|
||||
else:
|
||||
tests = __search_for_tests()
|
||||
|
||||
# let's move to the directory under test
|
||||
crt_dir = os.getcwd()
|
||||
os.chdir(dir_under_test)
|
||||
|
||||
# execute each module
|
||||
try:
|
||||
config.logger.debug("Discovered test clases: %s" % pprint.pformat(tests))
|
||||
suite = unittest.TestSuite()
|
||||
loader = unittest.TestLoader()
|
||||
result = unittest.TestResult()
|
||||
for m,t in tests:
|
||||
suite.addTest(loader.loadTestsFromName("%s.%s" % (m,t)))
|
||||
config.logger.info("Running %d test(s)", suite.countTestCases())
|
||||
suite.run(result)
|
||||
|
||||
if len(result.errors) > 0:
|
||||
map(lambda x: config.logger.error("Exception on test: %s" % pprint.pformat(x)), result.errors)
|
||||
|
||||
if len(result.failures) > 0:
|
||||
map(lambda x: config.logger.error("Failed test: %s:\n%s\n" % (pprint.pformat(x[0]), "\n".join(["-- %s" % x for x in eval(pprint.pformat(x[1])).split("\n")]))), result.failures)
|
||||
|
||||
config.logger.info("Test results: %d ran, %d errors, %d failures" % (result.testsRun, len(result.errors), len(result.failures)))
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
config.logger.error("Exception while running test. Tracedump: \n%s", traceback.format_exc(e))
|
||||
finally:
|
||||
os.chdir(crt_dir)
|
||||
return len(result.failures)
|
||||
|
||||
# verify that we had a branch-under-test name as parameter
|
||||
def validate_args():
|
||||
from optparse import OptionParser
|
||||
parser = OptionParser(usage="usage: %prog [options] branch_under_test")
|
||||
|
||||
parser.add_option("-t", "--test-dir", dest="testdir", default=None, help="Use specified directory to run tests, inhibits the checkout.")
|
||||
parser.add_option("-s", "--single", dest="singletest", default=None, help="Run only the specified test")
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
if len(args) < 1:
|
||||
raise Exception("Please specify the branch to run on. Use option '-h' when in doubt.")
|
||||
return (options, args)
|
||||
|
||||
|
||||
|
||||
|
||||
# load the configuration options
|
||||
def read_settings():
|
||||
if not os.path.exists(config.SETTINGS_FILE) or not os.path.isfile(config.SETTINGS_FILE):
|
||||
raise Exception("Config file '%s' cannot be openend" % config.SETTINGS_FILE);
|
||||
return json.loads(open(config.SETTINGS_FILE, "r").read())
|
||||
|
||||
|
||||
# cleanup !
|
||||
def clean_up(testdir):
|
||||
# TODO: delete the test dir
|
||||
#run_shell_cmd("rm -rf -- '%s'" % testdir)
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
(options, args) = validate_args()
|
||||
|
||||
settings = read_settings()
|
||||
need_cleanup = False
|
||||
|
||||
testdir = None
|
||||
no_failures = 1
|
||||
try:
|
||||
if options.testdir is not None and os.path.exists(options.testdir):
|
||||
testdir = options.testdir
|
||||
config.logger.info("No checkout, using %s" % testdir)
|
||||
else:
|
||||
need_cleanup = True
|
||||
testdir = set_up_test_branch(settings, args[0]) # we expect a branch name as first argument
|
||||
|
||||
config.testdir = testdir # we let tests know where to run
|
||||
no_failures = execute_tests(testdir, options.singletest)
|
||||
|
||||
except ShellCmdException as e :
|
||||
import traceback
|
||||
config.logger.error("Error while setting up testing. Traceback: \n%s" % traceback.format_exc(e))
|
||||
finally:
|
||||
if need_cleanup and testdir is not None:
|
||||
clean_up(testdir)
|
||||
|
||||
sys.exit(no_failures)
|
||||
20
bitbake/lib/toaster/contrib/tts/scratchpad.py
Normal file
20
bitbake/lib/toaster/contrib/tts/scratchpad.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import config
|
||||
|
||||
# Code testing section
|
||||
def _code_test():
|
||||
def callback_writeeventlog(opt, opt_str, value, parser):
|
||||
if len(parser.rargs) < 1 or parser.rargs[0].startswith("-"):
|
||||
value = ""
|
||||
else:
|
||||
value = parser.rargs[0]
|
||||
del parser.rargs[0]
|
||||
|
||||
setattr(parser.values, opt.dest, value)
|
||||
|
||||
parser = optparse.OptionParser()
|
||||
parser.add_option("-w", "--write-log", help = "Writes the event log of the build to a bitbake event json file.",
|
||||
action = "callback", callback=callback_writeeventlog, dest = "writeeventlog")
|
||||
|
||||
options, targets = parser.parse_args(sys.argv)
|
||||
|
||||
print (options, targets)
|
||||
5
bitbake/lib/toaster/contrib/tts/settings.json
Normal file
5
bitbake/lib/toaster/contrib/tts/settings.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"repo": "git@git.yoctoproject.org:poky-contrib",
|
||||
"localclone": "/home/ddalex/ssd/yocto/poky",
|
||||
"workdir": "/home/ddalex/ssd/yocto"
|
||||
}
|
||||
139
bitbake/lib/toaster/contrib/tts/shellutils.py
Normal file
139
bitbake/lib/toaster/contrib/tts/shellutils.py
Normal file
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
# Utilities shared by tests and other common bits of code.
|
||||
|
||||
import sys, os, subprocess, fcntl, errno
|
||||
import config
|
||||
from config import logger
|
||||
|
||||
|
||||
# License warning; this code is copied from the BitBake project, file bitbake/lib/bb/utils.py
|
||||
# The code is originally licensed GPL-2.0, and we redistribute it under still GPL-2.0
|
||||
|
||||
# End of copy is marked with #ENDOFCOPY marker
|
||||
|
||||
def mkdirhier(directory):
|
||||
"""Create a directory like 'mkdir -p', but does not complain if
|
||||
directory already exists like os.makedirs
|
||||
"""
|
||||
|
||||
try:
|
||||
os.makedirs(directory)
|
||||
except OSError as e:
|
||||
if e.errno != errno.EEXIST:
|
||||
raise e
|
||||
|
||||
def lockfile(name, shared=False, retry=True):
|
||||
"""
|
||||
Use the file fn as a lock file, return when the lock has been acquired.
|
||||
Returns a variable to pass to unlockfile().
|
||||
"""
|
||||
config.logger.debug("take lockfile %s" % name)
|
||||
dirname = os.path.dirname(name)
|
||||
mkdirhier(dirname)
|
||||
|
||||
if not os.access(dirname, os.W_OK):
|
||||
logger.error("Unable to acquire lock '%s', directory is not writable",
|
||||
name)
|
||||
sys.exit(1)
|
||||
|
||||
op = fcntl.LOCK_EX
|
||||
if shared:
|
||||
op = fcntl.LOCK_SH
|
||||
if not retry:
|
||||
op = op | fcntl.LOCK_NB
|
||||
|
||||
while True:
|
||||
# If we leave the lockfiles lying around there is no problem
|
||||
# but we should clean up after ourselves. This gives potential
|
||||
# for races though. To work around this, when we acquire the lock
|
||||
# we check the file we locked was still the lock file on disk.
|
||||
# by comparing inode numbers. If they don't match or the lockfile
|
||||
# no longer exists, we start again.
|
||||
|
||||
# This implementation is unfair since the last person to request the
|
||||
# lock is the most likely to win it.
|
||||
|
||||
try:
|
||||
lf = open(name, 'a+')
|
||||
fileno = lf.fileno()
|
||||
fcntl.flock(fileno, op)
|
||||
statinfo = os.fstat(fileno)
|
||||
if os.path.exists(lf.name):
|
||||
statinfo2 = os.stat(lf.name)
|
||||
if statinfo.st_ino == statinfo2.st_ino:
|
||||
return lf
|
||||
lf.close()
|
||||
except Exception:
|
||||
try:
|
||||
lf.close()
|
||||
except Exception:
|
||||
pass
|
||||
pass
|
||||
if not retry:
|
||||
return None
|
||||
|
||||
def unlockfile(lf):
|
||||
"""
|
||||
Unlock a file locked using lockfile()
|
||||
"""
|
||||
try:
|
||||
# If we had a shared lock, we need to promote to exclusive before
|
||||
# removing the lockfile. Attempt this, ignore failures.
|
||||
fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
os.unlink(lf.name)
|
||||
except (IOError, OSError):
|
||||
pass
|
||||
fcntl.flock(lf.fileno(), fcntl.LOCK_UN)
|
||||
lf.close()
|
||||
|
||||
#ENDOFCOPY
|
||||
|
||||
|
||||
def mk_lock_filename():
|
||||
our_name = os.path.basename(__file__)
|
||||
our_name = ".%s" % ".".join(reversed(our_name.split(".")))
|
||||
return config.LOCKFILE + our_name
|
||||
|
||||
|
||||
|
||||
class ShellCmdException(Exception):
|
||||
pass
|
||||
|
||||
def run_shell_cmd(command, cwd = None):
|
||||
if cwd is None:
|
||||
cwd = os.getcwd()
|
||||
|
||||
config.logger.debug("_shellcmd: (%s) %s" % (cwd, command))
|
||||
p = subprocess.Popen(command, cwd = cwd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(out,err) = p.communicate()
|
||||
p.wait()
|
||||
if p.returncode:
|
||||
if len(err) == 0:
|
||||
err = "command: %s \n%s" % (command, out)
|
||||
else:
|
||||
err = "command: %s \n%s" % (command, err)
|
||||
config.logger.warn("_shellcmd: error \n%s\n%s" % (out, err))
|
||||
raise ShellCmdException(err)
|
||||
else:
|
||||
#config.logger.debug("localhostbecontroller: shellcmd success\n%s" % out)
|
||||
return out
|
||||
|
||||
57
bitbake/lib/toaster/contrib/tts/tests.py
Normal file
57
bitbake/lib/toaster/contrib/tts/tests.py
Normal file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# ex:ts=4:sw=4:sts=4:et
|
||||
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
|
||||
#
|
||||
# Copyright (C) 2015 Alexandru Damian for Intel Corp.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License version 2 as
|
||||
# published by the Free Software Foundation.
|
||||
#
|
||||
# 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, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
|
||||
# Test definitions. The runner will look for and auto-discover the tests
|
||||
# no matter what they file are they in, as long as they are in the same directory
|
||||
# as this file.
|
||||
|
||||
import unittest
|
||||
from shellutils import *
|
||||
|
||||
class TestPyCompilable(unittest.TestCase):
|
||||
''' Verifies that all Python files are syntactically correct '''
|
||||
def test_compile_file(self):
|
||||
try:
|
||||
out = run_shell_cmd("find . -name *py -type f -print0 | xargs -0 -n1 -P20 python -m py_compile", config.testdir)
|
||||
except ShellCmdException as e:
|
||||
self.fail("Error compiling python files: %s" % (e))
|
||||
except Exception as e:
|
||||
self.fail("Unknown error: %s" % e)
|
||||
|
||||
|
||||
class TestPySystemStart(unittest.TestCase):
|
||||
''' Attempts to start Toaster, verify that it is succesfull, and stop it '''
|
||||
def setUp(self):
|
||||
run_shell_cmd("bash -c 'rm -f build/*log'")
|
||||
|
||||
def test_start_interactive_mode(self):
|
||||
try:
|
||||
run_shell_cmd("bash -c 'source %s/oe-init-build-env && source toaster start && source toaster stop'" % config.testdir, config.testdir)
|
||||
except ShellCmdException as e:
|
||||
self.fail("Failed starting interactive mode: %s" % (e))
|
||||
|
||||
def test_start_managed_mode(self):
|
||||
try:
|
||||
run_shell_cmd("./poky/bitbake/bin/toaster webport=56789 & sleep 10 && curl http://localhost:56789/ && kill -2 %1")
|
||||
pass
|
||||
except ShellCmdException as e:
|
||||
self.fail("Failed starting managed mode: %s" % (e))
|
||||
|
||||
87
bitbake/lib/toaster/contrib/tts/toasteruitest/run_toastertests.py
Executable file
87
bitbake/lib/toaster/contrib/tts/toasteruitest/run_toastertests.py
Executable file
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# Copyright
|
||||
|
||||
# DESCRIPTION
|
||||
# This is script for running all selected toaster cases on
|
||||
# selected web browsers manifested in toaster_test.cfg.
|
||||
|
||||
# 1. How to start toaster in yocto:
|
||||
# $ source poky/oe-init-build-env
|
||||
# $ source toaster start
|
||||
# $ bitbake core-image-minimal
|
||||
|
||||
# 2. How to install selenium on Ubuntu:
|
||||
# $ sudo apt-get install scrot python-pip
|
||||
# $ sudo pip install selenium
|
||||
|
||||
# 3. How to install selenium addon in firefox:
|
||||
# Download the lastest firefox addon from http://release.seleniumhq.org/selenium-ide/
|
||||
# Then install it. You can also install firebug and firepath addon
|
||||
|
||||
# 4. How to start writing a new case:
|
||||
# All you need to do is to implement the function test_xxx() and pile it on.
|
||||
|
||||
# 5. How to test with Chrome browser
|
||||
# Download/install chrome on host
|
||||
# Download chromedriver from https://code.google.com/p/chromedriver/downloads/list according to your host type
|
||||
# put chromedriver in PATH, (e.g. /usr/bin/, bear in mind to chmod)
|
||||
# For windows host, you may put chromedriver.exe in the same directory as chrome.exe
|
||||
|
||||
|
||||
import unittest, time, re, sys, getopt, os, logging, platform
|
||||
import ConfigParser
|
||||
import subprocess
|
||||
|
||||
|
||||
class toaster_run_all():
|
||||
def __init__(self):
|
||||
# in case this script is called from other directory
|
||||
os.chdir(os.path.abspath(sys.path[0]))
|
||||
self.starttime = time.strptime(time.ctime())
|
||||
self.parser = ConfigParser.SafeConfigParser()
|
||||
found = self.parser.read('toaster_test.cfg')
|
||||
self.host_os = platform.system().lower()
|
||||
self.run_all_cases()
|
||||
self.collect_log()
|
||||
|
||||
def get_test_cases(self):
|
||||
# we have config groups for different os type in toaster_test.cfg
|
||||
cases_to_run = eval(self.parser.get('toaster_test_' + self.host_os, 'test_cases'))
|
||||
return cases_to_run
|
||||
|
||||
|
||||
def run_all_cases(self):
|
||||
cases_temp = self.get_test_cases()
|
||||
for case in cases_temp:
|
||||
single_case_cmd = "python -m unittest toaster_automation_test.toaster_cases.test_" + str(case)
|
||||
print single_case_cmd
|
||||
subprocess.call(single_case_cmd, shell=True)
|
||||
|
||||
def collect_log(self):
|
||||
"""
|
||||
the log files are temporarily stored in ./log/tmp/..
|
||||
After all cases are done, they should be transfered to ./log/$TIMESTAMP/
|
||||
"""
|
||||
def comple(number):
|
||||
if number < 10:
|
||||
return str(0) + str(number)
|
||||
else:
|
||||
return str(number)
|
||||
now = self.starttime
|
||||
now_str = comple(now.tm_year) + comple(now.tm_mon) + comple(now.tm_mday) + \
|
||||
comple(now.tm_hour) + comple(now.tm_min) + comple(now.tm_sec)
|
||||
log_dir = os.path.abspath(sys.path[0]) + os.sep + 'log' + os.sep + now_str
|
||||
log_tmp_dir = os.path.abspath(sys.path[0]) + os.sep + 'log' + os.sep + 'tmp'
|
||||
try:
|
||||
os.renames(log_tmp_dir, log_dir)
|
||||
except OSError :
|
||||
logging.error(" Cannot create log dir(timestamp) under log, please check your privilege")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
toaster_run_all()
|
||||
|
||||
|
||||
|
||||
|
||||
1924
bitbake/lib/toaster/contrib/tts/toasteruitest/toaster_automation_test.py
Executable file
1924
bitbake/lib/toaster/contrib/tts/toasteruitest/toaster_automation_test.py
Executable file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
# Configuration file for toaster_test
|
||||
# Sorted by different host type
|
||||
|
||||
# test browser could be: firefox; chrome; ie(still under development)
|
||||
# logging_level could be: CRITICAL; ERROR; WARNING; INFO; DEBUG; NOTSET
|
||||
|
||||
|
||||
[toaster_test_linux]
|
||||
toaster_url = 'http://127.0.0.1:8000'
|
||||
test_browser = 'firefox'
|
||||
test_cases = [946]
|
||||
logging_level = 'INFO'
|
||||
|
||||
|
||||
[toaster_test_windows]
|
||||
toaster_url = 'http://127.0.0.1:8000'
|
||||
test_browser = ['ie', 'firefox', 'chrome']
|
||||
test_cases = [901, 902, 903]
|
||||
logging_level = 'DEBUG'
|
||||
|
||||
|
||||
44
bitbake/lib/toaster/contrib/tts/urlcheck.py
Normal file
44
bitbake/lib/toaster/contrib/tts/urlcheck.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
import httplib2
|
||||
import time
|
||||
|
||||
import config
|
||||
import urllist
|
||||
|
||||
# TODO: spawn server here
|
||||
BASEURL="http://localhost:8000/"
|
||||
|
||||
#def print_browserlog(url):
|
||||
# driver = webdriver.Firefox()
|
||||
# driver.get(url)
|
||||
# body = driver.find_element_by_tag_name("body")
|
||||
# body.send_keys(Keys.CONTROL + 't')
|
||||
# for i in driver.get_log('browser'):
|
||||
# print(i)
|
||||
# driver.close()
|
||||
|
||||
|
||||
# TODO: turn to a test
|
||||
def validate_html(url):
|
||||
h = httplib2.Http(".cache")
|
||||
# TODO: the w3c-validator must be a configurable setting
|
||||
urlrequest = "http://icarus.local/w3c-validator/check?doctype=HTML5&uri="+url
|
||||
try:
|
||||
resp, content = h.request(urlrequest, "HEAD")
|
||||
if resp['x-w3c-validator-status'] == "Abort":
|
||||
config.logger.error("FAILed call %s" % url)
|
||||
else:
|
||||
config.logger.error("url %s is %s\terrors %s warnings %s (check at %s)" % (url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings'], urlrequest))
|
||||
except Exception as e:
|
||||
config.logger.warn("Failed validation call: %s" % e.__str__())
|
||||
|
||||
print("done %s" % url)
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
validate_html(sys.argv[1])
|
||||
else:
|
||||
for url in urllist.URLS:
|
||||
validate_html(BASEURL+url)
|
||||
53
bitbake/lib/toaster/contrib/tts/urllist.py
Normal file
53
bitbake/lib/toaster/contrib/tts/urllist.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import config
|
||||
|
||||
URLS = [
|
||||
'toastergui/landing/',
|
||||
'toastergui/builds/',
|
||||
'toastergui/build/1',
|
||||
'toastergui/build/1/tasks/',
|
||||
'toastergui/build/1/tasks/1/',
|
||||
'toastergui/build/1/task/1',
|
||||
'toastergui/build/1/recipes/',
|
||||
'toastergui/build/1/recipe/1/active_tab/1',
|
||||
'toastergui/build/1/recipe/1',
|
||||
'toastergui/build/1/recipe_packages/1',
|
||||
'toastergui/build/1/packages/',
|
||||
'toastergui/build/1/package/1',
|
||||
'toastergui/build/1/package_built_dependencies/1',
|
||||
'toastergui/build/1/package_included_detail/1/1',
|
||||
'toastergui/build/1/package_included_dependencies/1/1',
|
||||
'toastergui/build/1/package_included_reverse_dependencies/1/1',
|
||||
'toastergui/build/1/target/1',
|
||||
'toastergui/build/1/target/1/targetpkg',
|
||||
'toastergui/dentries/build/1/target/1',
|
||||
'toastergui/build/1/target/1/dirinfo',
|
||||
'toastergui/build/1/target/1/dirinfo_filepath/_/bin/bash',
|
||||
'toastergui/build/1/configuration',
|
||||
'toastergui/build/1/configvars',
|
||||
'toastergui/build/1/buildtime',
|
||||
'toastergui/build/1/cpuusage',
|
||||
'toastergui/build/1/diskio',
|
||||
'toastergui/build/1/target/1/packagefile/1',
|
||||
'toastergui/newproject/',
|
||||
'toastergui/projects/',
|
||||
'toastergui/project/',
|
||||
'toastergui/project/1',
|
||||
'toastergui/project/1/configuration',
|
||||
'toastergui/project/1/builds/',
|
||||
'toastergui/project/1/layers/',
|
||||
'toastergui/project/1/layer/1',
|
||||
'toastergui/project/1/layer/',
|
||||
'toastergui/project/1/importlayer',
|
||||
'toastergui/project/1/targets/',
|
||||
'toastergui/project/1/machines/',
|
||||
'toastergui/xhr_build/',
|
||||
'toastergui/xhr_projectbuild/1/',
|
||||
'toastergui/xhr_projectinfo/',
|
||||
'toastergui/xhr_projectedit/1',
|
||||
'toastergui/xhr_configvaredit/1',
|
||||
'toastergui/xhr_datatypeahead/1',
|
||||
'toastergui/xhr_importlayer/',
|
||||
'toastergui/xhr_updatelayer/',
|
||||
'toastergui/project/1/buildrequest/1',
|
||||
'toastergui/',
|
||||
]
|
||||
Reference in New Issue
Block a user