Import gst-integration-testsuites
[platform/upstream/gstreamer.git] / subprojects / gst-integration-testsuites / testsuites / testsuiteutils.py
1 # -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
2 #
3 # Copyright (c) 2015, Thibault Saunier <thibault.saunier@collabora.com>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this program; if not, write to the
17 # Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18 # Boston, MA 02110-1301, USA.
19
20
21 import json
22 import os
23 import subprocess
24 import sys
25
26 from urllib.request import urlretrieve
27 from urllib.parse import quote
28
29 try:
30     from launcher.config import GST_VALIDATE_TESTSUITE_VERSION
31 except ImportError:
32     GST_VALIDATE_TESTSUITE_VERSION = "master"
33
34
35 last_message_length = 0
36
37 os.environ["GST_VALIDATE_CONFIG"] = os.path.abspath(
38     os.path.join(
39         os.path.dirname(__file__), "..", "integration-testsuites.config")) + os.pathsep + os.environ.get("GST_VALIDATE_CONFIG", "")
40
41
42 def message(string):
43     if sys.stdout.isatty():
44         global last_message_length
45         print('\r' + string + ' ' * max(0, last_message_length - len(string)), end='')
46         last_message_length = len(string)
47     else:
48         print(string)
49
50
51 def sizeof_fmt(num, suffix='B'):
52     for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
53         if abs(num) < 1024.0:
54             return "%3.1f%s%s" % (num, unit, suffix)
55         num /= 1024.0
56     return "%.1f%s%s" % (num, 'Yi', suffix)
57
58
59 URL = ""
60
61
62 def reporthook(blocknum, blocksize, totalsize):
63     global URL
64     readsofar = blocknum * blocksize
65     if totalsize > 0:
66         percent = readsofar * 1e2 / totalsize
67         s = "\r%s —%5.1f%% %s / %s" % (URL,
68                                        percent, sizeof_fmt(readsofar), sizeof_fmt(totalsize)) \
69             + ' ' * 50
70         message(s)
71     else:  # total size is unknown
72         message("read %d" % (readsofar,))
73
74
75 def download_files(assets_dir):
76     print("Downloading %s" % assets_dir if assets_dir else "all assets")
77     fdir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
78                                         '..', 'medias'))
79
80     with open(os.path.join(fdir, 'files.json'), 'r') as f:
81         files = json.load(f)
82
83     for f, ref_filesize in files:
84         if assets_dir and not f.startswith(assets_dir):
85             continue
86
87         fname = os.path.join(fdir, f)
88         if os.path.exists(fname) and os.path.getsize(fname) == ref_filesize:
89             message('%s... OK' % fname)
90             continue
91
92         os.makedirs(os.path.dirname(fname), exist_ok=True)
93         rpath = fname[len(fdir) + 1:]
94         global URL
95         URL = 'https://gstreamer.freedesktop.org/data/media/gst-integration-testsuite/' + \
96             quote(rpath)
97         if sys.stdout.isatty():
98             message("\rDownloading %s" % URL)
99             hook = reporthook
100         else:
101             message("Downloading %s" % URL)
102             hook = None
103         try:
104             urlretrieve(URL, fname, hook)
105         except BaseException:
106             print("\nCould not retieved %s" % URL)
107             raise
108
109         if os.path.getsize(fname) != ref_filesize:
110             print("ERROR: File %s expected size %s != %s, this should never happen!",
111                   fname, os.path.getsize(fname), ref_filesize)
112             exit(1)
113     print("")
114
115
116 def update_assets(options, assets_dir):
117     try:
118         if options.sync_version is not None:
119             sync_version = options.sync_version
120         else:
121             sync_version = GST_VALIDATE_TESTSUITE_VERSION
122         CHECKOUT_BRANCH_COMMAND = "git fetch origin && (git checkout origin/%s || git checkout tags/%s)" % (
123             sync_version, sync_version)
124         if options.force_sync:
125             subprocess.check_call(["git", "reset", "--hard"], cwd=assets_dir)
126         print("Checking out %s" % sync_version)
127         subprocess.check_call(CHECKOUT_BRANCH_COMMAND, shell=True, cwd=assets_dir)
128         download_files(os.path.basename(os.path.join(assets_dir)))
129     except Exception as e:
130         print("\nERROR: Could not update assets \n\n: %s" % e)
131
132         return False
133
134     return True