File: system.py

package info (click to toggle)
python-stem 1.2.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 4,568 kB
  • ctags: 2,036
  • sloc: python: 20,108; makefile: 127; sh: 3
file content (568 lines) | stat: -rw-r--r-- 18,084 bytes parent folder | download | duplicates (2)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""
Integration tests for the stem.util.system functions against the tor process
that we're running.
"""

import getpass
import os
import tempfile
import unittest

import stem.util.proc
import stem.util.system
import test.runner

try:
  # added in python 3.3
  from unittest.mock import Mock, patch
except ImportError:
  from mock import Mock, patch


IS_EXTRA_TOR_RUNNING = None


def filter_system_call(prefixes):
  """
  Provides a functor that passes calls on to the stem.util.system.call()
  function if it matches one of the prefixes, and acts as a no-op otherwise.
  """

  original_call = stem.util.system.call

  def _filter_system_call(command, default):
    for prefix in prefixes:
      if command.startswith(prefix):
        real_call_function = original_call
        return real_call_function(command)

  return _filter_system_call


def _has_port():
  """
  True if our test runner has a control port, False otherwise.
  """

  return test.runner.Torrc.PORT in test.runner.get_runner().get_options()


class TestSystem(unittest.TestCase):
  def test_is_available(self):
    """
    Checks the stem.util.system.is_available function.
    """

    # I have yet to see a platform without 'ls'

    if stem.util.system.is_windows():
      self.assertTrue(stem.util.system.is_available('dir'))
    else:
      self.assertTrue(stem.util.system.is_available('ls'))

    # but it would be kinda weird if this did...

    self.assertFalse(stem.util.system.is_available('blarg_and_stuff'))

  def test_is_running(self):
    """
    Checks the stem.util.system.is_running function.
    """

    if not stem.util.system.is_available('ps'):
      test.runner.skip(self, '(ps unavailable)')
      return

    self.assertTrue(stem.util.system.is_running('tor'))
    self.assertFalse(stem.util.system.is_running('blarg_and_stuff'))

  def test_get_pid_by_name(self):
    """
    Checks general usage of the stem.util.system.get_pid_by_name function. This
    will fail if there's other tor instances running.
    """

    if stem.util.system.is_windows():
      test.runner.skip(self, '(unavailable on windows)')
      return
    elif self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return

    tor_pid = test.runner.get_runner().get_pid()
    self.assertEquals(tor_pid, stem.util.system.get_pid_by_name('tor'))
    self.assertEquals(None, stem.util.system.get_pid_by_name('blarg_and_stuff'))

  def test_get_pid_by_name_pgrep(self):
    """
    Tests the get_pid_by_name function with a pgrep response.
    """

    if self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return
    elif not stem.util.system.is_available('pgrep'):
      test.runner.skip(self, '(pgrep unavailable)')
      return

    pgrep_prefix = stem.util.system.GET_PID_BY_NAME_PGREP % ''

    call_replacement = filter_system_call([pgrep_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_name('tor'))

  def test_get_pid_by_name_pidof(self):
    """
    Tests the get_pid_by_name function with a pidof response.
    """

    if self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return
    elif not stem.util.system.is_available('pidof'):
      test.runner.skip(self, '(pidof unavailable)')
      return

    pidof_prefix = stem.util.system.GET_PID_BY_NAME_PIDOF % ''

    call_replacement = filter_system_call([pidof_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_name('tor'))

  def test_get_pid_by_name_ps_linux(self):
    """
    Tests the get_pid_by_name function with the linux variant of ps.
    """

    if self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return
    elif not stem.util.system.is_available('ps'):
      test.runner.skip(self, '(ps unavailable)')
      return
    elif stem.util.system.is_bsd():
      test.runner.skip(self, '(linux only)')
      return

    ps_prefix = stem.util.system.GET_PID_BY_NAME_PS_LINUX % ''

    call_replacement = filter_system_call([ps_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_name('tor'))

  def test_get_pid_by_name_ps_bsd(self):
    """
    Tests the get_pid_by_name function with the bsd variant of ps.
    """

    if self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return
    elif not stem.util.system.is_available('ps'):
      test.runner.skip(self, '(ps unavailable)')
      return
    elif not stem.util.system.is_bsd():
      test.runner.skip(self, '(bsd only)')
      return

    ps_prefix = stem.util.system.GET_PID_BY_NAME_PS_BSD

    call_replacement = filter_system_call([ps_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_name('tor'))

  def test_get_pid_by_name_lsof(self):
    """
    Tests the get_pid_by_name function with a lsof response.
    """

    runner = test.runner.get_runner()
    if self._is_extra_tor_running():
      test.runner.skip(self, '(multiple tor instances)')
      return
    elif not stem.util.system.is_available('lsof'):
      test.runner.skip(self, '(lsof unavailable)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    lsof_prefix = stem.util.system.GET_PID_BY_NAME_LSOF % ''

    call_replacement = filter_system_call([lsof_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      our_tor_pid = test.runner.get_runner().get_pid()
      all_tor_pids = stem.util.system.get_pid_by_name('tor', multiple = True)

      if len(all_tor_pids) == 1:
        self.assertEquals(our_tor_pid, all_tor_pids[0])

  def test_get_pid_by_port(self):
    """
    Checks general usage of the stem.util.system.get_pid_by_port function.
    """

    runner = test.runner.get_runner()
    if stem.util.system.is_windows():
      test.runner.skip(self, '(unavailable on windows)')
      return
    elif not _has_port():
      test.runner.skip(self, '(test instance has no port)')
      return
    elif stem.util.system.is_mac():
      test.runner.skip(self, '(resolvers unavailable)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return
    elif not (stem.util.system.is_available('netstat') or
              stem.util.system.is_available('sockstat') or
              stem.util.system.is_available('lsof')):
      test.runner.skip(self, '(connection resolvers unavailable)')
      return

    tor_pid, tor_port = runner.get_pid(), test.runner.CONTROL_PORT
    self.assertEquals(tor_pid, stem.util.system.get_pid_by_port(tor_port))
    self.assertEquals(None, stem.util.system.get_pid_by_port(99999))

  def test_get_pid_by_port_netstat(self):
    """
    Tests the get_pid_by_port function with a netstat response.
    """

    runner = test.runner.get_runner()
    if not _has_port():
      test.runner.skip(self, '(test instance has no port)')
      return
    elif not stem.util.system.is_available('netstat'):
      test.runner.skip(self, '(netstat unavailable)')
      return
    elif stem.util.system.is_bsd() or stem.util.system.is_windows():
      test.runner.skip(self, '(linux only)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    netstat_prefix = stem.util.system.GET_PID_BY_PORT_NETSTAT

    call_replacement = filter_system_call([netstat_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_port(test.runner.CONTROL_PORT))

  def test_get_pid_by_port_sockstat(self):
    """
    Tests the get_pid_by_port function with a sockstat response.
    """

    runner = test.runner.get_runner()
    if not _has_port():
      test.runner.skip(self, '(test instance has no port)')
      return
    elif not stem.util.system.is_available('sockstat'):
      test.runner.skip(self, '(sockstat unavailable)')
      return
    elif not stem.util.system.is_bsd():
      test.runner.skip(self, '(bsd only)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    sockstat_prefix = stem.util.system.GET_PID_BY_PORT_SOCKSTAT % ''

    call_replacement = filter_system_call([sockstat_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_port(test.runner.CONTROL_PORT))

  def test_get_pid_by_port_lsof(self):
    """
    Tests the get_pid_by_port function with a lsof response.
    """

    runner = test.runner.get_runner()
    if not _has_port():
      test.runner.skip(self, '(test instance has no port)')
      return
    elif not stem.util.system.is_available('lsof'):
      test.runner.skip(self, '(lsof unavailable)')
      return
    elif stem.util.system.is_mac():
      test.runner.skip(self, '(resolvers unavailable)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    lsof_prefix = stem.util.system.GET_PID_BY_PORT_LSOF

    call_replacement = filter_system_call([lsof_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      tor_pid = test.runner.get_runner().get_pid()
      self.assertEquals(tor_pid, stem.util.system.get_pid_by_port(test.runner.CONTROL_PORT))

  def test_get_pid_by_open_file(self):
    """
    Checks the stem.util.system.get_pid_by_open_file function.
    """

    # check a directory that exists, but isn't claimed by any application
    tmpdir = tempfile.mkdtemp()
    self.assertEquals(None, stem.util.system.get_pid_by_open_file(tmpdir))

    # check a directory that doesn't exist
    os.rmdir(tmpdir)
    self.assertEquals(None, stem.util.system.get_pid_by_open_file(tmpdir))

  def test_get_cwd(self):
    """
    Checks general usage of the stem.util.system.get_cwd function.
    """

    runner = test.runner.get_runner()

    if stem.util.system.is_windows():
      test.runner.skip(self, '(unavailable on windows)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    runner_pid, tor_cwd = runner.get_pid(), runner.get_tor_cwd()
    self.assertEquals(tor_cwd, stem.util.system.get_cwd(runner_pid))
    self.assertEquals(None, stem.util.system.get_cwd(99999))

  def test_get_cwd_pwdx(self):
    """
    Tests the get_pid_by_cwd function with a pwdx response.
    """

    runner = test.runner.get_runner()

    if not stem.util.system.is_available('pwdx'):
      test.runner.skip(self, '(pwdx unavailable)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    # filter the call function to only allow this command

    pwdx_prefix = stem.util.system.GET_CWD_PWDX % ''

    call_replacement = filter_system_call([pwdx_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      runner_pid, tor_cwd = runner.get_pid(), runner.get_tor_cwd()
      self.assertEquals(tor_cwd, stem.util.system.get_cwd(runner_pid))

  def test_get_cwd_lsof(self):
    """
    Tests the get_pid_by_cwd function with a lsof response.
    """

    runner = test.runner.get_runner()

    if not stem.util.system.is_available('lsof'):
      test.runner.skip(self, '(lsof unavailable)')
      return
    elif not runner.is_ptraceable():
      test.runner.skip(self, '(DisableDebuggerAttachment is set)')
      return

    # filter the call function to only allow this command

    lsof_prefix = 'lsof -a -p '

    call_replacement = filter_system_call([lsof_prefix])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      runner_pid, tor_cwd = runner.get_pid(), runner.get_tor_cwd()
      self.assertEquals(tor_cwd, stem.util.system.get_cwd(runner_pid))

  def test_get_user_none(self):
    """
    Tests the get_user function when the process doesn't exist.
    """

    self.assertEqual(None, stem.util.system.get_user(None))
    self.assertEqual(None, stem.util.system.get_user(-5))
    self.assertEqual(None, stem.util.system.get_start_time(98765))

  def test_get_user_proc(self):
    """
    Tests the get_user function with a proc response.
    """

    if not stem.util.proc.is_available():
      test.runner.skip(self, '(proc unavailable)')
      return

    call_replacement = filter_system_call(['ps '])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      # we started our tor process so it should be running with the same user

      pid = test.runner.get_runner().get_pid()
      self.assertTrue(getpass.getuser(), stem.util.system.get_user(pid))

  @patch('stem.util.proc.is_available', Mock(return_value = False))
  def test_get_user_ps(self):
    """
    Tests the get_user function with a ps response.
    """

    if not stem.util.system.is_available('ps'):
      test.runner.skip(self, '(ps unavailable)')
      return

    pid = test.runner.get_runner().get_pid()
    self.assertTrue(getpass.getuser(), stem.util.system.get_user(pid))

  def test_get_start_time_none(self):
    """
    Tests the get_start_time function when the process doesn't exist.
    """

    self.assertEqual(None, stem.util.system.get_start_time(None))
    self.assertEqual(None, stem.util.system.get_start_time(-5))
    self.assertEqual(None, stem.util.system.get_start_time(98765))

  def test_get_start_time_proc(self):
    """
    Tests the get_start_time function with a proc response.
    """

    if not stem.util.proc.is_available():
      test.runner.skip(self, '(proc unavailable)')
      return

    call_replacement = filter_system_call(['ps '])

    with patch('stem.util.system.call') as call_mock:
      call_mock.side_effect = call_replacement

      pid = test.runner.get_runner().get_pid()
      self.assertTrue(stem.util.system.get_start_time(pid) >= 0)

  @patch('stem.util.proc.is_available', Mock(return_value = False))
  def test_get_start_time_ps(self):
    """
    Tests the get_start_time function with a ps response.
    """

    if not stem.util.system.is_available('ps'):
      test.runner.skip(self, '(ps unavailable)')
      return

    pid = test.runner.get_runner().get_pid()
    self.assertTrue(stem.util.system.get_start_time(pid) >= 0)

  def test_get_bsd_jail_id(self):
    """
    Exercises the stem.util.system.get_bsd_jail_id function, running through
    the failure case (since I'm not on BSD I can't really test this function
    properly).
    """

    self.assertEquals(0, stem.util.system.get_bsd_jail_id(99999))

  def test_expand_path(self):
    """
    Exercises the expand_path() method with actual runtime data.
    """

    # Some of the following tests get confused when ran as root. For instance,
    # in my case...
    #
    #   >>> os.path.expanduser('~')
    #   '/home/atagar'
    #
    #   >>> os.path.expanduser('~root')
    #   '/root'

    if getpass.getuser() == 'root':
      test.runner.skip(self, '(running as root)')
      return

    self.assertEquals(os.getcwd(), stem.util.system.expand_path('.'))
    self.assertEquals(os.getcwd(), stem.util.system.expand_path('./'))
    self.assertEquals(os.path.join(os.getcwd(), 'foo'), stem.util.system.expand_path('./foo'))

    home_dir, username = os.path.expanduser('~'), getpass.getuser()
    self.assertEquals(home_dir, stem.util.system.expand_path('~'))
    self.assertEquals(home_dir, stem.util.system.expand_path('~/'))
    self.assertEquals(home_dir, stem.util.system.expand_path('~%s' % username))
    self.assertEquals(os.path.join(home_dir, 'foo'), stem.util.system.expand_path('~%s/foo' % username))

  def test_set_process_name(self):
    """
    Exercises the get_process_name() and set_process_name() methods.
    """

    initial_name = stem.util.system.get_process_name()
    self.assertTrue('run_tests.py' in initial_name)

    try:
      stem.util.system.set_process_name('stem_integ')
      self.assertEqual('stem_integ', stem.util.system.get_process_name())
    finally:
      stem.util.system.set_process_name(initial_name)

  def _is_extra_tor_running(self):
    # Try to figure out if there's more than one tor instance running. This
    # check will fail if pgrep is unavailable (for instance on bsd) but this
    # isn't the end of the world. It's just used to skip tests if they should
    # legitemately fail.

    global IS_EXTRA_TOR_RUNNING

    if IS_EXTRA_TOR_RUNNING is None:
      if stem.util.system.is_windows():
        # TODO: not sure how to check for this on windows
        IS_EXTRA_TOR_RUNNING = False
      elif not stem.util.system.is_bsd():
        pgrep_results = stem.util.system.call(stem.util.system.GET_PID_BY_NAME_PGREP % 'tor')
        IS_EXTRA_TOR_RUNNING = len(pgrep_results) > 1
      else:
        ps_results = stem.util.system.call(stem.util.system.GET_PID_BY_NAME_PS_BSD)
        results = [r for r in ps_results if r.endswith(' tor')]
        IS_EXTRA_TOR_RUNNING = len(results) > 1

    return IS_EXTRA_TOR_RUNNING