summaryrefslogtreecommitdiffstats
path: root/scripts/automation/regression/functional_tests/scapy_pkt_builder_test.py
blob: 5d34e5df246c951afc28670ca7ba99519d972f3d (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/router/bin/python

import pkt_bld_general_test

#HACK FIX ME START
import sys
import os

CURRENT_PATH        = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(CURRENT_PATH, '../../../trex_control_plane/stl/'))
#HACK FIX ME END
from trex_stl_lib.trex_stl_packet_builder_scapy import *

from scapy.all import *
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools import assert_raises
from nose.tools import raises
import os
import random
import pprint

class CTRexPktBuilderSanitySCapy_Test(pkt_bld_general_test.CGeneralPktBld_Test):

    def setUp(self):
        pass

    def test_simple_vm1(self):
        raw1 = STLScVmRaw( [ STLVmFlowVar(name="a",min_value="16.0.0.1",max_value="16.0.0.10",init_value="16.0.0.1",size=4,op="inc"),
                             STLVmWrFlowVar(fv_name="a",pkt_offset= "IP.src"),
                             STLVmFixIpv4(offset = "IP")]
                          );

        pkt_builder = STLPktBuilder();

        py='5'*128
        pkt=Ether()/ \
                 IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)/IP()/py

        # set packet 
        pkt_builder.set_packet(pkt);
        pkt_builder.add_command ( raw1 )
        pkt_builder.compile();

        pkt_builder.dump_scripts ()

        print(pkt_builder.get_vm_data())

        assert_equal( pkt_builder.get_vm_data(), {'split_by_var': '', 'instructions': [{'name': 'a', 'max_value': 268435466, 'min_value': 268435457, 'init_value': 268435457, 'size': 4, 'type': 'flow_var', 'step':1,'op': 'inc'}, {'is_big_endian': True, 'pkt_offset': 26, 'type': 'write_flow_var',  'name': 'a', 'add_value': 0}, {'pkt_offset': 14, 'type': 'fix_checksum_ipv4'}]} )
                                                 


    def test_simple_no_vm1(self):

        pkt_builder = STLPktBuilder();

        py='5'*128
        pkt=Ether()/ \
                 IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)/IP()/py

        # set packet 
        pkt_builder.set_packet(pkt);

        pkt_builder.compile();

        pkt_builder.dump_scripts ()

        assert_equal( pkt_builder.get_vm_data(),
                {   'instructions': [ ],
                    'split_by_var': ''}
        )


    def test_simple_mac_default(self):

        pkt =  Ether()/IP()/UDP()


        pkt_builder = STLPktBuilder(pkt = pkt);

        assert_equal( pkt_builder.is_default_src_mac () ,True)
        assert_equal( pkt_builder.is_default_dst_mac () ,True)

        pkt =  Ether(src="00:00:00:00:00:01")/IP()/UDP()

        pkt_builder = STLPktBuilder(pkt = pkt);

        assert_equal( pkt_builder.is_default_src_mac (), False)
        assert_equal( pkt_builder.is_default_dst_mac (), True)

        pkt =  Ether(dst="00:00:00:00:00:01")/IP()/UDP()

        pkt_builder = STLPktBuilder(pkt = pkt);

        assert_equal( pkt_builder.is_default_src_mac (),True)
        assert_equal(  pkt_builder.is_default_dst_mac (),False)




    def test_simple_teredo(self):

        pkt =  Ether()/IP(src="16.0.0.1",dst="48.0.0.1")/UDP(dport=3797,sport=3544)/IPv6(src="2001:0:4137:9350:8000:f12a:b9c8:2815",dst="2001:4860:0:2001::68")/UDP(dport=12,sport=1025)/ICMPv6Unknown()

        pkt.build();
        p_utl=CTRexScapyPktUtl(pkt);

        assert_equal( p_utl.get_field_offet_by_str("IPv6.src"), (50,16) )
        assert_equal( p_utl.get_field_offet_by_str("IPv6.dst"), (66,16) )




    def test_simple_scapy_vlan(self):

        py='5'*(9)
        p1=Ether(src="00:00:00:01:00:00",dst="00:00:00:01:00:00")/ \
                 Dot1Q(vlan=12)/ \
                 Dot1Q(vlan=17)/ \
                 IP(src="10.0.0.10",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)/py

        p1.build();
        p1.dump_layers_offset()
        p1.show2();
        hexdump(p1);
        #wrpcap("ipv4_udp_9k.pcap", p1);

        p_utl=CTRexScapyPktUtl(p1);

        assert_equal(p_utl.get_pkt_layers(),"Ethernet:802.1Q:802.1Q:IP:UDP:Raw")
        assert_equal(p_utl.layer_offset("802.1Q",0),14);
        assert_equal(p_utl.layer_offset("802.1Q",1),18);
        assert_equal(p_utl.get_field_offet_by_str("802|1Q.vlan"),(14,0));
        assert_equal(p_utl.get_field_offet_by_str("802|1Q:1.vlan"),(18,0));
        assert_equal(p_utl.get_field_offet_by_str("IP.src"),(34,4));

    def test_simple_scapy_128_udp(self):
        """
        build 128 byte packet with 0x35 as pyld
        """


        pkt_size =128 
        p1=Ether(src="00:00:00:01:00:00",dst="00:00:00:01:00:00")/ \
                 IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)
        pyld_size=pkt_size-len(p1);

        pkt=p1/('5'*(pyld_size))

        pkt.show2();
        hexdump(pkt);
        assert_equal(len(pkt),128)

    def test_simple_scapy_9k_ip_len(self):
        """
        build 9k ipv4 len packet
        """


        ip_pkt_size =9*1024
        p_l2=Ether(src="00:00:00:01:00:00",dst="00:00:00:01:00:00");
        p_l3=    IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)
        pyld_size = ip_pkt_size-len(p_l3);

        pkt=p_l2/p_l3/('\x55'*(pyld_size))

        #pkt.show2();
        #hexdump(pkt);
        assert_equal(len(pkt),9*1024+14)

    def test_simple_scapy_ipv6_1(self):
        """
        build ipv6 packet 
        """

        print("start ")
        py='\x55'*(64)

        p=Ether()/IPv6()/UDP(dport=12,sport=1025)/py
        #p.build();
        #p.dump_layers_offset()
        hexdump(p);
        p.show2();

        p_utl=CTRexScapyPktUtl(p);

        assert_equal(p_utl.get_field_offet_by_str("IPv6.src"),(22,16));


    def test_simple_vm2(self):
        raw1 = STLScVmRaw( [ STLVmFlowVar(name="my_valn",min_value=0,max_value=10,init_value=2,size=1,op="inc"),
                             STLVmWrFlowVar (fv_name="my_valn",pkt_offset= "802|1Q.vlan" ,offset_fixup=3) # fix the offset as valn is bitfield and not supported right now 
                              ]
                          );

        pkt_builder = STLPktBuilder();

        py='5'*128
        pkt=Ether()/ \
        Dot1Q(vlan=12)/ \
                 IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)/IP()/py

        # set packet 
        pkt_builder.set_packet(pkt);
        pkt_builder.add_command ( raw1 )
        pkt_builder.compile();


        d= pkt_builder.get_vm_data()
        assert_equal(d['instructions'][1]['pkt_offset'],17)

    def test_simple_vm3(self):
        try:
            raw1 = STLScVmRaw( [ STLVmFlowVar(name="my_valn",min_value=0,max_value=10,init_value=2,size=1,op="inc"),
                                 STLVmWrFlowVar(fv_name="my_valn_err",pkt_offset= "802|1Q.vlan" ,offset_fixup=3) # fix the offset as valn is bitfield and not supported right now 
                                  ]
                              );
    
            pkt_builder = STLPktBuilder();
    
            py='5'*128
            pkt=Ether()/ \
            Dot1Q(vlan=12)/ \
                     IP(src="16.0.0.1",dst="48.0.0.1")/ \
                     UDP(dport=12,sport=1025)/IP()/py
    
            # set packet 
            pkt_builder.set_packet(pkt);
            pkt_builder.add_command ( raw1 )
            pkt_builder.compile();
    
    
            d= pkt_builder.get_vm_data()
        except  CTRexPacketBuildException as e:
            error=str(e) 
            assert_equal(error.find("[errcode:-11]"),0);

    def test_simple_tuple_gen(self):
        vm = STLScVmRaw( [ STLVmTupleGen(name="tuple"), # define tuple gen 
                           STLVmWrFlowVar(fv_name="tuple.ip", pkt_offset= "IP.src" ), # write ip to packet IP.src
                           STLVmFixIpv4(offset = "IP"),                                # fix checksum
                           STLVmWrFlowVar (fv_name="tuple.port", pkt_offset= "UDP.sport" )  #write udp.port
                          ]
                        );
        pkt_builder = STLPktBuilder();

        py='5'*128
        pkt=Ether()/ \
        Dot1Q(vlan=12)/ \
                 IP(src="16.0.0.1",dst="48.0.0.1")/ \
                 UDP(dport=12,sport=1025)/IP()/py

        # set packet 
        pkt_builder.set_packet(pkt);
        pkt_builder.add_command ( vm )
        pkt_builder.compile();
        d= pkt_builder.get_vm_data()
        pkt_builder.dump_vm_data_as_yaml()

        assert_equal(d['instructions'][1]['pkt_offset'],30)
        assert_equal(d['instructions'][3]['pkt_offset'],38)

    def test_simple_random_pkt_size(self):

        ip_pkt_size = 9*1024
        p_l2 = Ether();
        p_l3 = IP(src="16.0.0.1",dst="48.0.0.1")
        p_l4 = UDP(dport=12,sport=1025)
        pyld_size = ip_pkt_size-len(p_l3/p_l4);

        pkt =p_l2/p_l3/p_l4/('\x55'*(pyld_size))

        l3_len_fix =-(len(p_l2));
        l4_len_fix =-(len(p_l2/p_l3));

        vm = STLScVmRaw( [ STLVmFlowVar(name="fv_rand", min_value=64, max_value=len(pkt), size=2, op="random"),
                           STLVmTrimPktSize("fv_rand"), # total packet size
                           STLVmWrFlowVar(fv_name="fv_rand", pkt_offset= "IP.len", add_val=l3_len_fix), 
                           STLVmFixIpv4(offset = "IP"),                                # fix checksum
                           STLVmWrFlowVar(fv_name="fv_rand", pkt_offset= "UDP.len", add_val=l4_len_fix)  
                          ]
                       )
        pkt_builder = STLPktBuilder();

        # set packet 
        pkt_builder.set_packet(pkt);
        pkt_builder.add_command ( vm )
        pkt_builder.compile();
        d= pkt_builder.get_vm_data()
        pkt_builder.dump_vm_data_as_yaml()

        assert_equal(d['instructions'][0]['max_value'],9230)
        assert_equal(d['instructions'][2]['pkt_offset'],16)
        assert_equal(d['instructions'][4]['pkt_offset'],38)

    def test_simple_pkt_loader(self):
        p=RawPcapReader("functional_tests/golden/basic_imix_golden.cap")
        print("")
        for pkt in p:
            print(pkt[1])
            print(hexdump(str(pkt[0])))
            break;

    def test_simple_pkt_loader1(self):

        pkt_builder = STLPktBuilder(pkt = "functional_tests/golden/udp_590.cap", build_raw = False);
        print("")
        pkt_builder.dump_as_hex()
        r = pkt_builder.pkt_raw
        assert_equal(safe_ord(r[1]),0x50)
        assert_equal(safe_ord(r[0]),0x00)
        assert_equal(safe_ord(r[0x240]),0x16)
        assert_equal(safe_ord(r[0x24d]),0x79)
        assert_equal(len(r),590)

        print(len(r))

    def test_simple_pkt_loader2(self):

        pkt_builder = STLPktBuilder(pkt = "functional_tests/golden/basic_imix_golden.cap");
        assert_equal(pkt_builder.pkt_layers_desc (), "Ethernet:IP:UDP:Raw");

    def test_simple_pkt_loader3(self):

        #pkt_builder = STLPktBuilder(pkt = "stl/golden/basic_imix_golden.cap");
        #r = pkt_builder.pkt_raw
        #print ""
        #hexdump(str(r))


        #print pkt_builder.pkt_layers_desc ()


        #pkt_builder.set_packet(pkt);

        py='\x55'*(64)

        p=Ether()/IP()/UDP(dport=12,sport=1025)/py
        pkt_str = bytes(p);
        print("")
        hexdump(pkt_str);
        scapy_pkt = Ether(pkt_str);
        scapy_pkt.show2();

    def tearDown(self):
        pass


class CTRexPktBuilderScapy_Test(pkt_bld_general_test.CGeneralPktBld_Test):

    def setUp(self):
        pass;
        #self.pkt_bld = CTRexPktBuilder()
        #self.pkt_bld.add_pkt_layer("l2", dpkt.ethernet.Ethernet())
        #self.pp = pprint.PrettyPrinter(indent=4)

    def tearDown(self):
        pass


if __name__ == "__main__":
    pass
span class="k">class DaemonRunner_usage_exit_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.usage_exit method. """ def test_raises_system_exit(self): """ Should raise SystemExit exception. """ instance = self.test_instance argv = [self.test_program_path] self.assertRaises( SystemExit, instance._usage_exit, argv) def test_message_follows_conventional_format(self): """ Should emit a conventional usage message. """ instance = self.test_instance argv = [self.test_program_path] expected_stderr_output = """\ usage: {progname} ... """.format( progname=self.test_program_name) self.assertRaises( SystemExit, instance._usage_exit, argv) self.assertOutputCheckerMatch( expected_stderr_output, self.fake_stderr.getvalue()) class DaemonRunner_parse_args_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.parse_args method. """ def setUp(self): """ Set up test fixtures. """ super(DaemonRunner_parse_args_TestCase, self).setUp() func_patcher_usage_exit = mock.patch.object( daemon.runner.DaemonRunner, "_usage_exit", side_effect=NotImplementedError) func_patcher_usage_exit.start() self.addCleanup(func_patcher_usage_exit.stop) def test_emits_usage_message_if_insufficient_args(self): """ Should emit a usage message and exit if too few arguments. """ instance = self.test_instance argv = [self.test_program_path] exc = self.assertRaises( NotImplementedError, instance.parse_args, argv) daemon.runner.DaemonRunner._usage_exit.assert_called_with(argv) def test_emits_usage_message_if_unknown_action_arg(self): """ Should emit a usage message and exit if unknown action. """ instance = self.test_instance progname = self.test_program_name argv = [self.test_program_path, 'bogus'] exc = self.assertRaises( NotImplementedError, instance.parse_args, argv) daemon.runner.DaemonRunner._usage_exit.assert_called_with(argv) def test_should_parse_system_argv_by_default(self): """ Should parse sys.argv by default. """ instance = self.test_instance expected_action = 'start' argv = self.valid_argv_params['start'] with mock.patch.object(sys, "argv", new=argv): instance.parse_args() self.assertEqual(expected_action, instance.action) def test_sets_action_from_first_argument(self): """ Should set action from first commandline argument. """ instance = self.test_instance for name, argv in self.valid_argv_params.items(): expected_action = name instance.parse_args(argv) self.assertEqual(expected_action, instance.action) try: ProcessLookupError except NameError: # Python 2 uses OSError. ProcessLookupError = functools.partial(OSError, errno.ESRCH) class DaemonRunner_do_action_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.do_action method. """ def test_raises_error_if_unknown_action(self): """ Should emit a usage message and exit if action is unknown. """ instance = self.test_instance instance.action = 'bogus' expected_error = daemon.runner.DaemonRunnerInvalidActionError self.assertRaises( expected_error, instance.do_action) class DaemonRunner_do_action_start_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.do_action method, action 'start'. """ def setUp(self): """ Set up test fixtures. """ super(DaemonRunner_do_action_start_TestCase, self).setUp() self.test_instance.action = 'start' def test_raises_error_if_pidfile_locked(self): """ Should raise error if PID file is locked. """ instance = self.test_instance instance.daemon_context.open.side_effect = lockfile.AlreadyLocked pidfile_path = self.scenario['pidfile_path'] expected_error = daemon.runner.DaemonRunnerStartFailureError expected_message_content = pidfile_path exc = self.assertRaises( expected_error, instance.do_action) self.assertIn(expected_message_content, unicode(exc)) def test_breaks_lock_if_no_such_process(self): """ Should request breaking lock if PID file process is not running. """ set_runner_scenario(self, 'pidfile-locked') instance = self.test_instance self.mock_runner_lockfile.read_pid.return_value = ( self.scenario['pidlockfile_scenario']['pidfile_pid']) pidfile_path = self.scenario['pidfile_path'] test_pid = self.scenario['pidlockfile_scenario']['pidfile_pid'] expected_signal = signal.SIG_DFL test_error = ProcessLookupError("Not running") os.kill.side_effect = test_error instance.do_action() os.kill.assert_called_with(test_pid, expected_signal) self.mock_runner_lockfile.break_lock.assert_called_with() def test_requests_daemon_context_open(self): """ Should request the daemon context to open. """ instance = self.test_instance instance.do_action() instance.daemon_context.open.assert_called_with() def test_emits_start_message_to_stderr(self): """ Should emit start message to stderr. """ instance = self.test_instance expected_stderr = """\ started with pid {pid:d} """.format( pid=self.scenario['pid']) instance.do_action() self.assertOutputCheckerMatch( expected_stderr, self.fake_stderr.getvalue()) def test_requests_app_run(self): """ Should request the application to run. """ instance = self.test_instance instance.do_action() self.test_app.run.assert_called_with() class DaemonRunner_do_action_stop_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.do_action method, action 'stop'. """ def setUp(self): """ Set up test fixtures. """ super(DaemonRunner_do_action_stop_TestCase, self).setUp() set_runner_scenario(self, 'pidfile-locked') self.test_instance.action = 'stop' self.mock_runner_lockfile.is_locked.return_value = True self.mock_runner_lockfile.i_am_locking.return_value = False self.mock_runner_lockfile.read_pid.return_value = ( self.scenario['pidlockfile_scenario']['pidfile_pid']) def test_raises_error_if_pidfile_not_locked(self): """ Should raise error if PID file is not locked. """ set_runner_scenario(self, 'simple') instance = self.test_instance self.mock_runner_lockfile.is_locked.return_value = False self.mock_runner_lockfile.i_am_locking.return_value = False self.mock_runner_lockfile.read_pid.return_value = ( self.scenario['pidlockfile_scenario']['pidfile_pid']) pidfile_path = self.scenario['pidfile_path'] expected_error = daemon.runner.DaemonRunnerStopFailureError expected_message_content = pidfile_path exc = self.assertRaises( expected_error, instance.do_action) self.assertIn(expected_message_content, unicode(exc)) def test_breaks_lock_if_pidfile_stale(self): """ Should break lock if PID file is stale. """ instance = self.test_instance pidfile_path = self.scenario['pidfile_path'] test_pid = self.scenario['pidlockfile_scenario']['pidfile_pid'] expected_signal = signal.SIG_DFL test_error = OSError(errno.ESRCH, "Not running") os.kill.side_effect = test_error instance.do_action() self.mock_runner_lockfile.break_lock.assert_called_with() def test_sends_terminate_signal_to_process_from_pidfile(self): """ Should send SIGTERM to the daemon process. """ instance = self.test_instance test_pid = self.scenario['pidlockfile_scenario']['pidfile_pid'] expected_signal = signal.SIGTERM instance.do_action() os.kill.assert_called_with(test_pid, expected_signal) def test_raises_error_if_cannot_send_signal_to_process(self): """ Should raise error if cannot send signal to daemon process. """ instance = self.test_instance test_pid = self.scenario['pidlockfile_scenario']['pidfile_pid'] pidfile_path = self.scenario['pidfile_path'] test_error = OSError(errno.EPERM, "Nice try") os.kill.side_effect = test_error expected_error = daemon.runner.DaemonRunnerStopFailureError expected_message_content = unicode(test_pid) exc = self.assertRaises( expected_error, instance.do_action) self.assertIn(expected_message_content, unicode(exc)) @mock.patch.object(daemon.runner.DaemonRunner, "_start") @mock.patch.object(daemon.runner.DaemonRunner, "_stop") class DaemonRunner_do_action_restart_TestCase(DaemonRunner_BaseTestCase): """ Test cases for DaemonRunner.do_action method, action 'restart'. """ def setUp(self): """ Set up test fixtures. """ super(DaemonRunner_do_action_restart_TestCase, self).setUp() set_runner_scenario(self, 'pidfile-locked') self.test_instance.action = 'restart' def test_requests_stop_then_start( self, mock_func_daemonrunner_start, mock_func_daemonrunner_stop): """ Should request stop, then start. """ instance = self.test_instance instance.do_action() mock_func_daemonrunner_start.assert_called_with() mock_func_daemonrunner_stop.assert_called_with() @mock.patch.object(sys, "stderr") class emit_message_TestCase(scaffold.TestCase): """ Test cases for ‘emit_message’ function. """ def test_writes_specified_message_to_stream(self, mock_stderr): """ Should write specified message to stream. """ test_message = self.getUniqueString() expected_content = "{message}\n".format(message=test_message) daemon.runner.emit_message(test_message, stream=mock_stderr) mock_stderr.write.assert_called_with(expected_content) def test_writes_to_specified_stream(self, mock_stderr): """ Should write message to specified stream. """ test_message = self.getUniqueString() mock_stream = mock.MagicMock() daemon.runner.emit_message(test_message, stream=mock_stream) mock_stream.write.assert_called_with(mock.ANY) def test_writes_to_stderr_by_default(self, mock_stderr): """ Should write message to ‘sys.stderr’ by default. """ test_message = self.getUniqueString() daemon.runner.emit_message(test_message) mock_stderr.write.assert_called_with(mock.ANY) class is_pidfile_stale_TestCase(scaffold.TestCase): """ Test cases for ‘is_pidfile_stale’ function. """ def setUp(self): """ Set up test fixtures. """ super(is_pidfile_stale_TestCase, self).setUp() func_patcher_os_kill = mock.patch.object(os, "kill") func_patcher_os_kill.start() self.addCleanup(func_patcher_os_kill.stop) os.kill.return_value = None self.test_pid = self.getUniqueInteger() self.test_pidfile = mock.MagicMock(daemon.pidfile.TimeoutPIDLockFile) self.test_pidfile.read_pid.return_value = self.test_pid def test_returns_false_if_no_pid_in_file(self): """ Should return False if the pidfile contains no PID. """ self.test_pidfile.read_pid.return_value = None expected_result = False result = daemon.runner.is_pidfile_stale(self.test_pidfile) self.assertEqual(expected_result, result) def test_returns_false_if_process_exists(self): """ Should return False if the process with its PID exists. """ expected_result = False result = daemon.runner.is_pidfile_stale(self.test_pidfile) self.assertEqual(expected_result, result) def test_returns_true_if_process_does_not_exist(self): """ Should return True if the process does not exist. """ test_error = ProcessLookupError("No such process") del os.kill.return_value os.kill.side_effect = test_error expected_result = True result = daemon.runner.is_pidfile_stale(self.test_pidfile) self.assertEqual(expected_result, result) # Local variables: # coding: utf-8 # mode: python # End: # vim: fileencoding=utf-8 filetype=python :