aboutsummaryrefslogtreecommitdiffstats
path: root/tools/dftestlib/dftest.py
blob: 4b54df142844ce9458c78b89f8d6fd15ad19ce5d (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu>
#
# SPDX-License-Identifier: GPL-2.0-or-later


import os
import tempfile
import unittest

from dftestlib import util

# The binaries to use. We assume we are running
# from the top of the wireshark distro
TSHARK = os.path.join(os.getenv("WS_BIN_PATH", "."), "tshark")

class DFTest(unittest.TestCase):
    """Base class for all tests in this dfilter-test collection."""

    # Remove these file when finished (in tearDownClass)
    files_to_remove = []

    @classmethod
    def setUpClass(cls):
        """Create the trace file to be used in the tests."""
        assert cls.trace_file

        # if the class sets the 'trace_file' field, then it
        # names the trace file to use for the tests. It *should*
        # reside in dftestfiles
        assert not os.path.isabs(cls.trace_file)
        cls.trace_file = os.path.join(os.getenv("SOURCE_DIR", "."), "tools",
                "dftestfiles", cls.trace_file)

    @classmethod
    def tearDownClass(cls):
        """Remove the trace file used in the tests."""
        for filename in cls.files_to_remove:
            if os.path.exists(filename):
                try:
                    os.remove(filename)
                except OSError:
                    pass


    def runDFilter(self, dfilter):
        # Create the tshark command
        cmdv = [TSHARK,
                "-n",       # No name resolution
                "-r",       # Next arg is trace file to read
                self.trace_file,
                "-Y",       # packet display filter (used to be -R)
                dfilter]

        (status, output) = util.exec_cmdv(cmdv)
        return status, output


    def assertDFilterCount(self, dfilter, expected_count):
        """Run a display filter and expect a certain number of packets."""

        (status, output) = self.runDFilter(dfilter)

        # tshark must succeed
        self.assertEqual(status, util.SUCCESS, output)

        # Split the output (one big string) into lines, removing
        # empty lines (extra newline at end of output)
        lines = [L for L in output.split("\n") if L != ""]

        msg = "Expected %d, got: %s" % (expected_count, output)
        self.assertEqual(len(lines), expected_count, msg)

    def assertDFilterFail(self, dfilter):
        """Run a display filter and expect tshark to fail"""

        (status, output) = self.runDFilter(dfilter)

        # tshark must succeed
        self.assertNotEqual(status, util.SUCCESS, output)