aboutsummaryrefslogtreecommitdiff
path: root/test/sca/utils.py
blob: ad77d21e5778ba7e9d682af85fd4b8a8a781f9e8 (plain)
1
2
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
35
36
37
38
39
40
41
42
from os import mkdir, getenv, getcwd
from os.path import join, exists, split
from typing import Dict
from unittest import TestCase

import matplotlib.pyplot as plt

from pyecsca.sca import Trace

force_plot = True


cases: Dict[str, int] = {}


class Plottable(TestCase):
    def get_dir(self):
        if split(getcwd())[1] == "test":
            directory = "plots"
        else:
            directory = join("test", "plots")
        if not exists(directory):
            mkdir(directory)
        return directory

    def get_fname(self):
        directory = self.get_dir()
        case_id = cases.setdefault(self.id(), 0) + 1
        cases[self.id()] = case_id
        return join(directory, self.id() + str(case_id))

    def plot(self, *traces: Trace, **kwtraces: Trace):
        if not force_plot and getenv("PYECSCA_TEST_PLOTS") is None:
            return
        fig = plt.figure()
        ax = fig.add_subplot(111)
        for i, trace in enumerate(traces):
            ax.plot(trace.samples, label=str(i))
        for name, trace in kwtraces.items():
            ax.plot(trace.samples, label=name)
        ax.legend(loc="best")
        plt.savefig(self.get_fname() + ".png")