utils.py 4.74 KB
Newer Older
1
2
# vim: set fileencoding=utf-8 :

Samuel GAIST's avatar
Samuel GAIST committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
###################################################################################
#                                                                                 #
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/               #
# Contact: beat.support@idiap.ch                                                  #
#                                                                                 #
# Redistribution and use in source and binary forms, with or without              #
# modification, are permitted provided that the following conditions are met:     #
#                                                                                 #
# 1. Redistributions of source code must retain the above copyright notice, this  #
# list of conditions and the following disclaimer.                                #
#                                                                                 #
# 2. Redistributions in binary form must reproduce the above copyright notice,    #
# this list of conditions and the following disclaimer in the documentation       #
# and/or other materials provided with the distribution.                          #
#                                                                                 #
# 3. Neither the name of the copyright holder nor the names of its contributors   #
# may be used to endorse or promote products derived from this software without   #
# specific prior written permission.                                              #
#                                                                                 #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND #
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED   #
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE          #
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE    #
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL      #
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      #
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER      #
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,   #
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   #
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.            #
#                                                                                 #
###################################################################################

35
36
37
38
39

"""
Helper functions to run tests
"""

40
import logging
Samuel GAIST's avatar
Samuel GAIST committed
41
42
import os
import pdb  # noqa
43
import sys
44
45
46

from beat.core.experiment import Experiment
from beat.core.hash import hashDataset
Samuel GAIST's avatar
Samuel GAIST committed
47
from beat.core.hash import toPath
48

Samuel GAIST's avatar
Samuel GAIST committed
49
50
from . import prefix
from . import tmp_prefix
51
52


53
def set_trace():
Samuel GAIST's avatar
Samuel GAIST committed
54
55
56
57
    """This is the currently official way to start pdb while in a click command"""

    pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace()  # noqa

58

59
60
61
62
63
64
65
def index_experiment_dbs(experiment_name):
    """
    Index all databases for given experiment
    """

    experiment = Experiment(prefix, experiment_name)

Samuel GAIST's avatar
Samuel GAIST committed
66
67
68
69
70
71
    if not experiment.valid:
        raise RuntimeError(
            "Invalid experiment:{}\n{}".format(
                experiment_name, "\n  * %s" % "\n  * ".join(experiment.errors)
            )
        )
72
73

    for block_name, infos in experiment.datasets.items():
Samuel GAIST's avatar
Samuel GAIST committed
74
75
76
77
78
        view = infos["database"].view(infos["protocol"], infos["set"])
        filename = toPath(
            hashDataset(infos["database"].name, infos["protocol"], infos["set"]),
            suffix=".db",
        )
79
        view.index(os.path.join(tmp_prefix, filename))
80
81
82
83
84
85
86
87
88
89
90
91


# Based on https://stackoverflow.com/a/20553331/5843716
class MockLoggingHandler(logging.Handler):
    """Mock logging handler to check for expected logs.

    Messages are available from an instance's ``messages`` dict, in order,
    indexed by a lowercase log level string (e.g., 'debug', 'info', etc.).
    """

    def __init__(self, *args, **kwargs):
        self.messages = {
Samuel GAIST's avatar
Samuel GAIST committed
92
93
94
95
96
97
            "debug": [],
            "info": [],
            "warning": [],
            "error": [],
            "critical": [],
            "extra": [],
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        }
        super(MockLoggingHandler, self).__init__(*args, **kwargs)

    def emit(self, record):
        "Store a message from ``record`` in the instance's ``messages`` dict."
        try:
            self.messages[record.levelname.lower()].append(record.getMessage())
        except Exception:
            self.handleError(record)

    def reset(self):
        self.acquire()
        try:
            for message_list in self.messages.values():
                message_list.clear()
        finally:
            self.release()