Beispiel #1
0
  def test_the_little_relay_that_could(self):
    def tutorial_example():
      from stem.control import Controller

      with Controller.from_port(control_port = 9051) as controller:
        controller.authenticate()  # provide the password here if you set one

        bytes_read = controller.get_info("traffic/read")
        bytes_written = controller.get_info("traffic/written")

        print "My Tor relay has read %s bytes and written %s." % (bytes_read, bytes_written)

    controller = mocking.get_object(Controller, {
      'authenticate': mocking.no_op(),
      'close': mocking.no_op(),
      'get_info': mocking.return_for_args({
        ('traffic/read',): '33406',
        ('traffic/written',): '29649',
      }, is_method = True),
    })

    mocking.mock(
      Controller.from_port, mocking.return_value(controller),
      target_module = Controller,
      is_static = True,
    )

    tutorial_example()
    self.assertEqual("My Tor relay has read 33406 bytes and written 29649.\n", self.stdout.getvalue())
Beispiel #2
0
    def test_load_processed_files(self):
        """
    Successful load of content.
    """

        test_lines = (
            "/dir/ 0",
            "/dir/file 12345",
            "/dir/file with spaces 7138743",
            "  /dir/with extra space 12345   ",
            "   \t   ",
            "",
            "/dir/after empty line 12345",
        )

        expected_value = {
            "/dir/": 0,
            "/dir/file": 12345,
            "/dir/file with spaces": 7138743,
            "/dir/with extra space": 12345,
            "/dir/after empty line": 12345,
        }

        test_content = StringIO.StringIO("\n".join(test_lines))
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertEquals(expected_value,
                          stem.descriptor.reader.load_processed_files(""))
Beispiel #3
0
  def test_mirror_mirror_on_the_wall_1(self):
    def tutorial_example():
      from stem.control import Controller

      with Controller.from_port(control_port = 9051) as controller:
        controller.authenticate()

        for desc in controller.get_network_statuses():
          print "found relay %s (%s)" % (desc.nickname, desc.fingerprint)

    controller = mocking.get_object(Controller, {
      'authenticate': mocking.no_op(),
      'close': mocking.no_op(),
      'get_network_statuses': mocking.return_value(
        [mocking.get_router_status_entry_v2()],
      ),
    })

    mocking.mock(
      Controller.from_port, mocking.return_value(controller),
      target_module = Controller,
      is_static = True,
    )

    tutorial_example()
    self.assertEqual("found relay caerSidi (A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB)\n", self.stdout.getvalue())
Beispiel #4
0
  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 % ""
    mocking.mock(stem.util.system.call, filter_system_call([lsof_prefix]))

    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])
Beispiel #5
0
    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 % ""
        mocking.mock(stem.util.system.call,
                     filter_system_call([sockstat_prefix]))

        tor_pid = test.runner.get_runner().get_pid()
        self.assertEquals(
            tor_pid,
            stem.util.system.get_pid_by_port(test.runner.CONTROL_PORT))
Beispiel #6
0
    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
        mocking.mock(stem.util.system.call, filter_system_call([lsof_prefix]))

        tor_pid = test.runner.get_runner().get_pid()
        self.assertEquals(
            tor_pid,
            stem.util.system.get_pid_by_port(test.runner.CONTROL_PORT))
Beispiel #7
0
  def test_get_protocolinfo(self):
    """
    Exercises the get_protocolinfo() method.
    """

    # Use the handy mocked protocolinfo response.
    mocking.mock(stem.connection.get_protocolinfo, mocking.return_value(
      mocking.get_protocolinfo_response()
    ))
    # Compare the str representation of these object, because the class
    # does not have, nor need, a direct comparison operator.
    self.assertEqual(str(mocking.get_protocolinfo_response()), str(self.controller.get_protocolinfo()))

    # Raise an exception in the stem.connection.get_protocolinfo() call.
    mocking.mock(stem.connection.get_protocolinfo, mocking.raise_exception(ProtocolError))

    # Get a default value when the call fails.

    self.assertEqual(
      "default returned",
      self.controller.get_protocolinfo(default = "default returned")
    )

    # No default value, accept the error.
    self.assertRaises(ProtocolError, self.controller.get_protocolinfo)
Beispiel #8
0
    def test_load_processed_files(self):
        """
    Successful load of content.
    """

        test_lines = (
            "/dir/ 0",
            "/dir/file 12345",
            "/dir/file with spaces 7138743",
            "  /dir/with extra space 12345   ",
            "   \t   ",
            "",
            "/dir/after empty line 12345",
        )

        expected_value = {
            "/dir/": 0,
            "/dir/file": 12345,
            "/dir/file with spaces": 7138743,
            "/dir/with extra space": 12345,
            "/dir/after empty line": 12345,
        }

        test_content = StringIO.StringIO("\n".join(test_lines))
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertEquals(expected_value, stem.descriptor.reader.load_processed_files(""))
Beispiel #9
0
    def test_mirror_mirror_on_the_wall_1(self):
        def tutorial_example():
            from stem.control import Controller

            with Controller.from_port(control_port=9051) as controller:
                controller.authenticate()

                for desc in controller.get_network_statuses():
                    print "found relay %s (%s)" % (desc.nickname,
                                                   desc.fingerprint)

        controller = mocking.get_object(
            Controller, {
                'authenticate':
                mocking.no_op(),
                'close':
                mocking.no_op(),
                'get_network_statuses':
                mocking.return_value([mocking.get_router_status_entry_v2()], ),
            })

        mocking.mock(
            Controller.from_port,
            mocking.return_value(controller),
            target_module=Controller,
            is_static=True,
        )

        tutorial_example()
        self.assertEqual(
            "found relay caerSidi (A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB)\n",
            self.stdout.getvalue())
Beispiel #10
0
    def test_mirror_mirror_on_the_wall_2(self):
        def tutorial_example():
            from stem.descriptor import parse_file

            for desc in parse_file(open("/home/atagar/.tor/cached-consensus")):
                print "found relay %s (%s)" % (desc.nickname, desc.fingerprint)

        test_file = io.BytesIO(
            mocking.get_network_status_document_v3(
                routers=[mocking.get_router_status_entry_v3()],
                content=True,
            ))

        mocking.support_with(test_file)
        test_file.name = "/home/atagar/.tor/cached-consensus"

        if is_python_3():
            import builtins
            mocking.mock(open,
                         mocking.return_value(test_file),
                         target_module=builtins)
        else:
            mocking.mock(open, mocking.return_value(test_file))

        tutorial_example()
        self.assertEqual(
            "found relay caerSidi (A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB)\n",
            self.stdout.getvalue())
Beispiel #11
0
    def test_get_protocolinfo(self):
        """
    Exercises the get_protocolinfo() method.
    """

        # Use the handy mocked protocolinfo response.
        mocking.mock(stem.connection.get_protocolinfo,
                     mocking.return_value(mocking.get_protocolinfo_response()))
        # Compare the str representation of these object, because the class
        # does not have, nor need, a direct comparison operator.
        self.assertEqual(str(mocking.get_protocolinfo_response()),
                         str(self.controller.get_protocolinfo()))

        # Raise an exception in the stem.connection.get_protocolinfo() call.
        mocking.mock(stem.connection.get_protocolinfo,
                     mocking.raise_exception(ProtocolError))

        # Get a default value when the call fails.

        self.assertEqual(
            "default returned",
            self.controller.get_protocolinfo(default="default returned"))

        # No default value, accept the error.
        self.assertRaises(ProtocolError, self.controller.get_protocolinfo)
Beispiel #12
0
  def test_get_pid_by_port_sockstat(self):
    """
    Tests the get_pid_by_port function with a sockstat response.
    """

    mocking.mock(system.call, mock_call(system.GET_PID_BY_PORT_SOCKSTAT % 9051, GET_PID_BY_PORT_SOCKSTAT_RESULTS))
    self.assertEquals(4397, system.get_pid_by_port(9051))
    self.assertEquals(4397, system.get_pid_by_port("9051"))
    self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #13
0
def _mock_open(content):
  test_content = StringIO.StringIO(content)
  mocking.support_with(test_content)

  if stem.prereq.is_python_3():
    import builtins
    mocking.mock(builtins.open, mocking.return_value(test_content), builtins)
  else:
    mocking.mock(open, mocking.return_value(test_content))
Beispiel #14
0
  def test_mirror_mirror_on_the_wall_4(self):
    def tutorial_example():
      from stem.control import Controller
      from stem.util import str_tools

      # provides a mapping of observed bandwidth to the relay nicknames
      def get_bw_to_relay():
        bw_to_relay = {}

        with Controller.from_port(control_port = 9051) as controller:
          controller.authenticate()

          for desc in controller.get_server_descriptors():
            if desc.exit_policy.is_exiting_allowed():
              bw_to_relay.setdefault(desc.observed_bandwidth, []).append(desc.nickname)

        return bw_to_relay

      # prints the top fifteen relays

      bw_to_relay = get_bw_to_relay()
      count = 1

      for bw_value in sorted(bw_to_relay.keys(), reverse = True):
        for nickname in bw_to_relay[bw_value]:
          print "%i. %s (%s/s)" % (count, nickname, str_tools.get_size_label(bw_value, 2))
          count += 1

          if count > 15:
            return

    exit_descriptor = mocking.get_relay_server_descriptor({
      'router': 'speedyexit 149.255.97.109 9001 0 0'
    }, content = True).replace(b'reject *:*', b'accept *:*')

    exit_descriptor = mocking.sign_descriptor_content(exit_descriptor)
    exit_descriptor = RelayDescriptor(exit_descriptor)

    controller = mocking.get_object(Controller, {
      'authenticate': mocking.no_op(),
      'close': mocking.no_op(),
      'get_server_descriptors': mocking.return_value([
        exit_descriptor,
        mocking.get_relay_server_descriptor(),  # non-exit
        exit_descriptor,
        exit_descriptor,
      ])
    })

    mocking.mock(
      Controller.from_port, mocking.return_value(controller),
      target_module = Controller,
      is_static = True,
    )

    tutorial_example()
    self.assertEqual(MIRROR_MIRROR_OUTPUT, self.stdout.getvalue())
Beispiel #15
0
  def test_get_pid_by_open_file_lsof(self):
    """
    Tests the get_pid_by_open_file function with a lsof response.
    """

    lsof_query = system.GET_PID_BY_FILE_LSOF % "/tmp/foo"
    mocking.mock(system.call, mock_call(lsof_query, ["4762"]))
    self.assertEquals(4762, system.get_pid_by_open_file("/tmp/foo"))
    self.assertEquals(None, system.get_pid_by_open_file("/tmp/somewhere_else"))
Beispiel #16
0
    def test_load_processed_files_empty(self):
        """
    Tests the load_processed_files() function with an empty file.
    """

        test_content = StringIO.StringIO("")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertEquals({}, stem.descriptor.reader.load_processed_files(""))
Beispiel #17
0
    def test_load_processed_files_empty(self):
        """
    Tests the load_processed_files() function with an empty file.
    """

        test_content = StringIO.StringIO("")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertEquals({}, stem.descriptor.reader.load_processed_files(""))
Beispiel #18
0
  def test_get_pid_by_port_netstat(self):
    """
    Tests the get_pid_by_port function with a netstat response.
    """

    mocking.mock(system.call, mock_call(system.GET_PID_BY_PORT_NETSTAT, GET_PID_BY_PORT_NETSTAT_RESULTS))
    self.assertEquals(1641, system.get_pid_by_port(9051))
    self.assertEquals(1641, system.get_pid_by_port("9051"))
    self.assertEquals(None, system.get_pid_by_port(631))
    self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #19
0
    def test_load_processed_files_malformed_timestamp(self):
        """
    Tests the load_processed_files() function content that is malformed because
    it has a non-numeric timestamp.
    """

        test_content = StringIO.StringIO("/dir/file 123a")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertRaises(TypeError, stem.descriptor.reader.load_processed_files, "")
Beispiel #20
0
  def test_get_pid_by_port_lsof(self):
    """
    Tests the get_pid_by_port function with a lsof response.
    """

    mocking.mock(system.call, mock_call(system.GET_PID_BY_PORT_LSOF, GET_PID_BY_PORT_LSOF_RESULTS))
    self.assertEquals(1745, system.get_pid_by_port(9051))
    self.assertEquals(1745, system.get_pid_by_port("9051"))
    self.assertEquals(329, system.get_pid_by_port(80))
    self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #21
0
  def test_get_system_start_time(self):
    """
    Tests the get_system_start_time function.
    """

    mocking.mock(proc._get_line, mocking.return_for_args({
      ('/proc/stat', 'btime', 'system start time'): 'btime 1001001',
    }))

    self.assertEquals(1001001, proc.get_system_start_time())
Beispiel #22
0
  def test_get_cwd(self):
    """
    Tests the get_cwd function with a given pid.
    """

    mocking.mock(os.readlink, mocking.return_for_args({
      ('/proc/24019/cwd',): '/home/directory/TEST'
    }), os)

    self.assertEquals('/home/directory/TEST', proc.get_cwd(24019))
Beispiel #23
0
    def test_load_processed_files_malformed_file(self):
        """
    Tests the load_processed_files() function content that is malformed because
    it has an invalid file path.
    """

        test_content = StringIO.StringIO("not_an_absolute_file 12345")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertRaises(TypeError, stem.descriptor.reader.load_processed_files, "")
Beispiel #24
0
  def test_get_pid_by_name_ps_bsd(self):
    """
    Tests the get_pid_by_name function with the bsd variant of ps.
    """

    mocking.mock(system.is_bsd, mocking.return_true())
    mocking.mock(system.call, mock_call(system.GET_PID_BY_NAME_PS_BSD, GET_PID_BY_NAME_PS_BSD))
    self.assertEquals(1, system.get_pid_by_name("launchd"))
    self.assertEquals(11, system.get_pid_by_name("DirectoryService"))
    self.assertEquals(None, system.get_pid_by_name("blarg"))
Beispiel #25
0
def _mock_open(content):
    test_content = StringIO.StringIO(content)
    mocking.support_with(test_content)

    if stem.prereq.is_python_3():
        import builtins
        mocking.mock(builtins.open, mocking.return_value(test_content),
                     builtins)
    else:
        mocking.mock(open, mocking.return_value(test_content))
Beispiel #26
0
    def test_get_pid_by_open_file_lsof(self):
        """
    Tests the get_pid_by_open_file function with a lsof response.
    """

        lsof_query = system.GET_PID_BY_FILE_LSOF % "/tmp/foo"
        mocking.mock(system.call, mock_call(lsof_query, ["4762"]))
        self.assertEquals(4762, system.get_pid_by_open_file("/tmp/foo"))
        self.assertEquals(None,
                          system.get_pid_by_open_file("/tmp/somewhere_else"))
Beispiel #27
0
  def test_get_physical_memory(self):
    """
    Tests the get_physical_memory function.
    """

    mocking.mock(proc._get_line, mocking.return_for_args({
      ('/proc/meminfo', 'MemTotal:', 'system physical memory'): 'MemTotal:       12345 kB',
    }))

    self.assertEquals((12345 * 1024), proc.get_physical_memory())
Beispiel #28
0
    def test_load_processed_files_malformed_timestamp(self):
        """
    Tests the load_processed_files() function content that is malformed because
    it has a non-numeric timestamp.
    """

        test_content = StringIO.StringIO("/dir/file 123a")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertRaises(TypeError,
                          stem.descriptor.reader.load_processed_files, "")
Beispiel #29
0
    def test_load_processed_files_malformed_file(self):
        """
    Tests the load_processed_files() function content that is malformed because
    it has an invalid file path.
    """

        test_content = StringIO.StringIO("not_an_absolute_file 12345")
        mocking.support_with(test_content)
        mocking.mock(open, mocking.return_value(test_content))
        self.assertRaises(TypeError,
                          stem.descriptor.reader.load_processed_files, "")
Beispiel #30
0
    def test_get_cwd_lsof(self):
        """
    Tests the get_cwd function with a lsof response.
    """

        responses = {"75717": ["p75717", "n/Users/atagar/tor/src/or"], "1234": ["malformed output"], "7878": None}

        mocking.mock(system.call, mock_call(system.GET_CWD_LSOF, responses))

        for test_input in responses:
            expected_response = "/Users/atagar/tor/src/or" if test_input == "75717" else None
            self.assertEquals(expected_response, system.get_cwd(test_input))
Beispiel #31
0
  def test_get_memory_usage(self):
    """
    Tests the get_memory_usage function with a given pid.
    """

    mocking.mock(proc._get_lines, mocking.return_for_args({
      ('/proc/1111/status', ('VmRSS:', 'VmSize:'), 'memory usage'):
        {'VmRSS:': 'VmRSS: 100 kB', 'VmSize:': 'VmSize: 1800 kB'}
    }))

    self.assertEqual((0, 0), proc.get_memory_usage(0))
    self.assertEqual((100 * 1024, 1800 * 1024), proc.get_memory_usage(1111))
Beispiel #32
0
    def test_get_pid_by_name_ps_bsd(self):
        """
    Tests the get_pid_by_name function with the bsd variant of ps.
    """

        mocking.mock(system.is_bsd, mocking.return_true())
        mocking.mock(
            system.call,
            mock_call(system.GET_PID_BY_NAME_PS_BSD, GET_PID_BY_NAME_PS_BSD))
        self.assertEquals(1, system.get_pid_by_name("launchd"))
        self.assertEquals(11, system.get_pid_by_name("DirectoryService"))
        self.assertEquals(None, system.get_pid_by_name("blarg"))
Beispiel #33
0
    def test_get_pid_by_port_sockstat(self):
        """
    Tests the get_pid_by_port function with a sockstat response.
    """

        mocking.mock(
            system.call,
            mock_call(system.GET_PID_BY_PORT_SOCKSTAT % 9051,
                      GET_PID_BY_PORT_SOCKSTAT_RESULTS))
        self.assertEquals(4397, system.get_pid_by_port(9051))
        self.assertEquals(4397, system.get_pid_by_port("9051"))
        self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #34
0
  def test_get_uid(self):
    """
    Tests the get_uid function with a given pid.
    """

    for test_value in [(24019, 11111), (0, 22222)]:
      pid, uid = test_value
      mocking.mock(proc._get_line, mocking.return_for_args({
        ("/proc/%s/status" % pid, 'Uid:', 'uid'): 'Uid: %s' % uid
      }))

      self.assertEquals(uid, proc.get_uid(pid))
Beispiel #35
0
    def test_get_pid_by_port_lsof(self):
        """
    Tests the get_pid_by_port function with a lsof response.
    """

        mocking.mock(
            system.call,
            mock_call(system.GET_PID_BY_PORT_LSOF,
                      GET_PID_BY_PORT_LSOF_RESULTS))
        self.assertEquals(1745, system.get_pid_by_port(9051))
        self.assertEquals(1745, system.get_pid_by_port("9051"))
        self.assertEquals(329, system.get_pid_by_port(80))
        self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #36
0
    def test_get_pid_by_port_netstat(self):
        """
    Tests the get_pid_by_port function with a netstat response.
    """

        mocking.mock(
            system.call,
            mock_call(system.GET_PID_BY_PORT_NETSTAT,
                      GET_PID_BY_PORT_NETSTAT_RESULTS))
        self.assertEquals(1641, system.get_pid_by_port(9051))
        self.assertEquals(1641, system.get_pid_by_port("9051"))
        self.assertEquals(None, system.get_pid_by_port(631))
        self.assertEquals(None, system.get_pid_by_port(123))
Beispiel #37
0
  def test_get_pid_by_name_lsof(self):
    """
    Tests the get_pid_by_name function with lsof responses.
    """

    responses = dict(GET_PID_BY_NAME_BASE_RESULTS)
    responses["success"] = ["1111"]
    responses["multiple_results"] = ["123", "456", "789"]
    mocking.mock(system.call, mock_call(system.GET_PID_BY_NAME_LSOF, responses))

    for test_input in responses:
      expected_response = 1111 if test_input == "success" else None
      self.assertEquals(expected_response, system.get_pid_by_name(test_input))
Beispiel #38
0
    def test_take_ownership_via_pid(self):
        """
    Checks that the tor process quits after we do if we set take_ownership. To
    test this we spawn a process and trick tor into thinking that it is us.
    """

        if not stem.prereq.is_python_26() and stem.util.system.is_windows():
            test.runner.skip(self, "(unable to kill subprocesses)")
            return
        elif not stem.util.system.is_available("sleep"):
            test.runner.skip(self, "('sleep' command is unavailable)")
            return
        elif test.runner.only_run_once(self, "test_take_ownership_via_pid"):
            return
        elif test.runner.require_version(
                self, stem.version.Requirement.TAKEOWNERSHIP):
            return

        # Have os.getpid provide the pid of a process we can safely kill. I hate
        # needing to a _get_pid() helper but after much head scratching I haven't
        # been able to mock os.getpid() or posix.getpid().

        sleep_process = subprocess.Popen(['sleep', '60'])
        mocking.mock(stem.process._get_pid,
                     mocking.return_value(str(sleep_process.pid)))

        tor_process = stem.process.launch_tor_with_config(
            tor_cmd=test.runner.get_runner().get_tor_command(),
            config={
                'SocksPort': '2777',
                'ControlPort': '2778',
                'DataDirectory': DATA_DIRECTORY,
            },
            completion_percent=5,
            take_ownership=True,
        )

        # Kill the sleep command. Tor should quit shortly after.

        _kill_process(sleep_process)

        # tor polls for the process every fifteen seconds so this may take a
        # while...

        for seconds_waited in xrange(30):
            if tor_process.poll() == 0:
                return  # tor exited

            time.sleep(1)

        self.fail("tor didn't quit after the process that owned it terminated")
Beispiel #39
0
  def test_get_pid_by_name_ps_linux(self):
    """
    Tests the get_pid_by_name function with the linux variant of ps.
    """

    mocking.mock(system.is_bsd, mocking.return_false())
    responses = dict(GET_PID_BY_NAME_BASE_RESULTS)
    responses["success"] = ["PID", " 1111"]
    responses["multiple_results"] = ["PID", " 123", " 456", " 789"]
    mocking.mock(system.call, mock_call(system.GET_PID_BY_NAME_PS_LINUX, responses))

    for test_input in responses:
      expected_response = 1111 if test_input == "success" else None
      self.assertEquals(expected_response, system.get_pid_by_name(test_input))
Beispiel #40
0
  def test_get_stats(self):
    """
    Tests get_stats() with all combinations of stat_type arguments.
    """

    # list of all combinations of args with respective return values
    stat_combinations = mocking.get_all_combinations([
      ('command', 'test_program'),
      ('utime', '0.13'),
      ('stime', '0.14'),
      ('start time', '10.21'),
    ])

    stat_path = "/proc/24062/stat"
    stat = '1 (test_program) 2 3 4 5 6 7 8 9 10 11 12 13.0 14.0 15 16 17 18 19 20 21.0 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43'

    mocking.mock(proc.get_system_start_time, mocking.return_value(10))

    # tests the case where no stat_types are specified
    mocking.mock(proc._get_line, mocking.return_for_args({
      (stat_path, '24062', 'process '): stat
    }))

    self.assertEquals((), proc.get_stats(24062))

    for stats in stat_combinations:
      # the stats variable is...
      #   [(arg1, resp1), (arg2, resp2)...]
      #
      # but we need...
      #   (arg1, arg2...), (resp1, resp2...).

      args, response = zip(*stats)

      mocking.mock(proc._get_line, mocking.return_for_args({
        (stat_path, '24062', 'process %s' % ', '.join(args)): stat
      }))

      self.assertEquals(response, proc.get_stats(24062, *args))

      # tests the case where pid = 0

      if 'start time' in args:
        response = 10
      else:
        response = ()

        for arg in args:
          if arg == 'command':
            response += ('sched',)
          elif arg == 'utime':
            response += ('0',)
          elif arg == 'stime':
            response += ('0',)

      mocking.mock(proc._get_line, mocking.return_for_args({
        ('/proc/0/stat', '0', 'process %s' % ', '.join(args)): stat
      }))

      self.assertEquals(response, proc.get_stats(0, *args))
Beispiel #41
0
 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:
     self.skipTest("(multiple tor instances)")
   elif not stem.util.system.is_available("pgrep"):
     self.skipTest("(pgrep unavailable)")
   
   pgrep_prefix = stem.util.system.GET_PID_BY_NAME_PGREP % ""
   mocking.mock(stem.util.system.call, filter_system_call([pgrep_prefix]))
   
   tor_pid = test.runner.get_runner().get_pid()
   self.assertEquals(tor_pid, stem.util.system.get_pid_by_name("tor"))
Beispiel #42
0
    def test_get_pid_by_name_lsof(self):
        """
    Tests the get_pid_by_name function with lsof responses.
    """

        responses = dict(GET_PID_BY_NAME_BASE_RESULTS)
        responses["success"] = ["1111"]
        responses["multiple_results"] = ["123", "456", "789"]
        mocking.mock(system.call,
                     mock_call(system.GET_PID_BY_NAME_LSOF, responses))

        for test_input in responses:
            expected_response = 1111 if test_input == "success" else None
            self.assertEquals(expected_response,
                              system.get_pid_by_name(test_input))
Beispiel #43
0
  def test_mirror_mirror_on_the_wall_3(self):
    def tutorial_example():
      from stem.descriptor.reader import DescriptorReader

      with DescriptorReader(["/home/atagar/server-descriptors-2013-03.tar"]) as reader:
        for desc in reader:
          print "found relay %s (%s)" % (desc.nickname, desc.fingerprint)

    mocking.mock(
      DescriptorReader.__iter__,
      mocking.return_value(iter([mocking.get_relay_server_descriptor()])),
      target_module = DescriptorReader
    )

    tutorial_example()
    self.assertEqual("found relay caerSidi (None)\n", self.stdout.getvalue())
Beispiel #44
0
    def test_get_pid_by_name_ps_linux(self):
        """
    Tests the get_pid_by_name function with the linux variant of ps.
    """

        mocking.mock(system.is_bsd, mocking.return_false())
        responses = dict(GET_PID_BY_NAME_BASE_RESULTS)
        responses["success"] = ["PID", " 1111"]
        responses["multiple_results"] = ["PID", " 123", " 456", " 789"]
        mocking.mock(system.call,
                     mock_call(system.GET_PID_BY_NAME_PS_LINUX, responses))

        for test_input in responses:
            expected_response = 1111 if test_input == "success" else None
            self.assertEquals(expected_response,
                              system.get_pid_by_name(test_input))
Beispiel #45
0
    def test_get_cwd_lsof(self):
        """
    Tests the get_cwd function with a lsof response.
    """

        responses = {
            "75717": ["p75717", "n/Users/atagar/tor/src/or"],
            "1234": ["malformed output"],
            "7878": None,
        }

        mocking.mock(system.call, mock_call(system.GET_CWD_LSOF, responses))

        for test_input in responses:
            expected_response = "/Users/atagar/tor/src/or" if test_input == "75717" else None
            self.assertEquals(expected_response, system.get_cwd(test_input))
Beispiel #46
0
 def test_take_ownership_via_pid(self):
   """
   Checks that the tor process quits after we do if we set take_ownership. To
   test this we spawn a process and trick tor into thinking that it is us.
   """
   
   if not stem.prereq.is_python_26() and stem.util.system.is_windows():
     test.runner.skip(self, "(unable to kill subprocesses)")
     return
   elif not stem.util.system.is_available("sleep"):
     test.runner.skip(self, "('sleep' command is unavailable)")
     return
   elif test.runner.only_run_once(self, "test_take_ownership_via_pid"): return
   elif test.runner.require_version(self, stem.version.Requirement.TAKEOWNERSHIP): return
   
   # Have os.getpid provide the pid of a process we can safely kill. I hate
   # needing to a _get_pid() helper but after much head scratching I haven't
   # been able to mock os.getpid() or posix.getpid().
   
   sleep_process = subprocess.Popen(['sleep', '60'])
   mocking.mock(stem.process._get_pid, mocking.return_value(str(sleep_process.pid)))
   
   tor_process = stem.process.launch_tor_with_config(
     tor_cmd = test.runner.get_runner().get_tor_command(),
     config = {
       'SocksPort': '2777',
       'ControlPort': '2778',
       'DataDirectory': DATA_DIRECTORY,
     },
     completion_percent = 5,
     take_ownership = True,
   )
   
   # Kill the sleep command. Tor should quit shortly after.
   
   _kill_process(sleep_process)
   
   # tor polls for the process every fifteen seconds so this may take a
   # while...
   
   for seconds_waited in xrange(30):
     if tor_process.poll() == 0:
       return # tor exited
     
     time.sleep(1)
   
   self.fail("tor didn't quit after the process that owned it terminated")
Beispiel #47
0
 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:
     self.skipTest("(multiple tor instances)")
   elif not stem.util.system.is_available("ps"):
     self.skipTest("(ps unavailable)")
   elif not stem.util.system.is_bsd():
     self.skipTest("(bsd only)")
   
   ps_prefix = stem.util.system.GET_PID_BY_NAME_PS_BSD
   mocking.mock(stem.util.system.call, filter_system_call([ps_prefix]))
   
   tor_pid = test.runner.get_runner().get_pid()
   self.assertEquals(tor_pid, stem.util.system.get_pid_by_name("tor"))
Beispiel #48
0
 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"):
     self.skipTest("(lsof unavailable)")
   elif not runner.is_ptraceable():
     self.skipTest("(DisableDebuggerAttachment is set)")
   
   # filter the call function to only allow this command
   lsof_prefix = "lsof -a -p "
   mocking.mock(stem.util.system.call, filter_system_call([lsof_prefix]))
   
   runner_pid, tor_cwd = runner.get_pid(), runner.get_tor_cwd()
   self.assertEquals(tor_cwd, stem.util.system.get_cwd(runner_pid))
Beispiel #49
0
    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 % ""
        mocking.mock(stem.util.system.call, filter_system_call([pidof_prefix]))

        tor_pid = test.runner.get_runner().get_pid()
        self.assertEquals(tor_pid, stem.util.system.get_pid_by_name("tor"))
Beispiel #50
0
  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 % ""
    mocking.mock(stem.util.system.call, filter_system_call([pidof_prefix]))

    tor_pid = test.runner.get_runner().get_pid()
    self.assertEquals(tor_pid, stem.util.system.get_pid_by_name("tor"))
Beispiel #51
0
    def test_expand_path_unix(self):
        """
    Tests the expand_path function. This does not exercise home directory
    expansions since that deals with our environment (that's left to integ
    tests).
    """

        mocking.mock(platform.system, mocking.return_value("Linux"))
        mocking.mock(os.path.join, posixpath.join, os.path)

        self.assertEquals("", system.expand_path(""))
        self.assertEquals("/tmp", system.expand_path("/tmp"))
        self.assertEquals("/tmp", system.expand_path("/tmp/"))
        self.assertEquals("/tmp", system.expand_path(".", "/tmp"))
        self.assertEquals("/tmp", system.expand_path("./", "/tmp"))
        self.assertEquals("/tmp/foo", system.expand_path("foo", "/tmp"))
        self.assertEquals("/tmp/foo", system.expand_path("./foo", "/tmp"))
Beispiel #52
0
    def test_get_cwd_pwdx(self):
        """
    Tests the get_cwd function with a pwdx response.
    """

        responses = {
            "3799": ["3799: /home/atagar"],
            "5839": ["5839: No such process"],
            "1234": ["malformed output"],
            "7878": None,
        }

        mocking.mock(system.call, mock_call(system.GET_CWD_PWDX, responses))

        for test_input in responses:
            expected_response = "/home/atagar" if test_input == "3799" else None
            self.assertEquals(expected_response, system.get_cwd(test_input))
Beispiel #53
0
    def test_take_ownership_via_pid(self):
        """
    Checks that the tor process quits after we do if we set take_ownership. To
    test this we spawn a process and trick tor into thinking that it is us.
    """

        if not stem.util.system.is_available("sleep"):
            test.runner.skip(self, "('sleep' command is unavailable)")
            return
        elif test.runner.only_run_once(self, "test_take_ownership_via_pid"):
            return
        elif test.runner.require_version(
                self, stem.version.Requirement.TAKEOWNERSHIP):
            return

        sleep_process = subprocess.Popen(['sleep', '60'])
        mocking.mock(os.getpid,
                     mocking.return_value(str(sleep_process.pid)),
                     target_module=os)

        tor_process = stem.process.launch_tor_with_config(
            tor_cmd=test.runner.get_runner().get_tor_command(),
            config={
                'SocksPort': '2777',
                'ControlPort': '2778',
                'DataDirectory': self.data_directory,
            },
            completion_percent=5,
            take_ownership=True,
        )

        # Kill the sleep command. Tor should quit shortly after.

        _kill_process(sleep_process)

        # tor polls for the process every fifteen seconds so this may take a
        # while...

        for seconds_waited in xrange(30):
            if tor_process.poll() == 0:
                return  # tor exited

            time.sleep(1)

        self.fail("tor didn't quit after the process that owned it terminated")
Beispiel #54
0
    def test_expand_path_windows(self):
        """
    Tests the expand_path function on windows. This does not exercise
    home directory expansions since that deals with our environment
    (that's left to integ tests).
    """

        mocking.mock(platform.system, mocking.return_value("Windows"))
        mocking.mock(os.path.join, ntpath.join, os.path)

        self.assertEquals("", system.expand_path(""))
        self.assertEquals("C:\\tmp", system.expand_path("C:\\tmp"))
        self.assertEquals("C:\\tmp", system.expand_path("C:\\tmp\\"))
        self.assertEquals("C:\\tmp", system.expand_path(".", "C:\\tmp"))
        self.assertEquals("C:\\tmp", system.expand_path(".\\", "C:\\tmp"))
        self.assertEquals("C:\\tmp\\foo", system.expand_path("foo", "C:\\tmp"))
        self.assertEquals("C:\\tmp\\foo",
                          system.expand_path(".\\foo", "C:\\tmp"))