"""
Implementation
"""

import os as _os
import shlex as _shlex

import setuptools.command.test as orig

class PyTest(orig.test):
	user_options = [
		('extras', None, "Install (all) setuptools extras when running tests"),
		('index-url=', None, "Specify an index url from which to retrieve "
			"dependencies"),
		('allow-hosts=', None, "Whitelist of comma-separated hosts to allow "
			"when retrieving dependencies"),
		('addopts=', None, "Additional options to be passed verbatim to the "
			"pytest runner")
	]

	def initialize_options(self):
		self.extras = False
		self.index_url = None
		self.allow_hosts = None
		self.addopts = []

	def finalize_options(self):
		if self.addopts:
			self.addopts = _shlex.split(self.addopts)

	def run(self):
		"""
		Override run to ensure requirements are available in this session (but
		don't install them anywhere).
		"""
		self._build_egg_fetcher()
		if self.distribution.install_requires:
			self.distribution.fetch_build_eggs(self.distribution.install_requires)
		if self.distribution.tests_require:
			self.distribution.fetch_build_eggs(self.distribution.tests_require)
		if self.distribution.extras_require and self.extras:
			list(map(self.distribution.fetch_build_eggs,
				self.distribution.extras_require.values()))
		if self.dry_run:
			self.announce('skipping tests (dry run)')
			return
		self.with_project_on_sys_path(self.run_tests)
		if self.result_code:
			raise SystemExit(self.result_code)
		return self.result_code

	def _build_egg_fetcher(self):
		"""Build an egg fetcher that respects index_url and allow_hosts"""
		# modified from setuptools.dist:Distribution.fetch_build_egg
		from setuptools.command.easy_install import easy_install
		main_dist = self.distribution
		# construct a fake distribution to store the args for easy_install
		dist = main_dist.__class__({'script_args': ['easy_install']})
		dist.parse_config_files()
		opts = dist.get_option_dict('easy_install')
		keep = (
			'find_links', 'site_dirs', 'index_url', 'optimize',
			'site_dirs', 'allow_hosts'
		)
		for key in opts.keys():
			if key not in keep:
				del opts[key]   # don't use any other settings
		if main_dist.dependency_links:
			links = main_dist.dependency_links[:]
			if 'find_links' in opts:
				links = opts['find_links'][1].split() + links
			opts['find_links'] = ('setup', links)
		if self.allow_hosts:
			opts['allow_hosts'] = ('test', self.allow_hosts)
		if self.index_url:
			opts['index_url'] = ('test', self.index_url)
		install_dir_func = getattr(dist, 'get_egg_cache_dir', _os.getcwd)
		install_dir = install_dir_func()
		cmd = easy_install(
			dist, args=["x"], install_dir=install_dir, exclude_scripts=True,
			always_copy=False, build_directory=None, editable=False,
			upgrade=False, multi_version=True, no_report = True
		)
		cmd.ensure_finalized()
		main_dist._egg_fetcher = cmd

	def run_tests(self):
		"""
		Override run_tests to invoke pytest.
		"""
		import pytest
		import sys
		# hide command-line arguments from pytest.main
		argv_saved = list(sys.argv)
		sys.argv[1:] = self.addopts
		self.result_code = pytest.main()
		sys.argv[:] = argv_saved

@@ -61,47 +61,305 @@
 lex%0A
-%0Aimport setuptools.command.test as orig
+import contextlib as _contextlib%0Aimport sys as _sys%0A%0Aimport setuptools.command.test as orig%0A%0A@_contextlib.contextmanager%0Adef _save_argv(repl=None):%0A    saved = _sys.argv%5B:%5D%0A    if repl is not None:%0A        _sys.argv%5B:%5D = repl%0A    try:%0A        yield saved%0A    finally:%0A        _sys.argv%5B:%5D = saved%0A
 %0A%0Acl
@@ -3132,161 +3132,64 @@
 %22%0A%09%09
-Override run_tests to invoke pytest.%0A%09%09%22%22%22%0A%09%09import pytest%0A%09%09import sys%0A%09%09# hide command-line arguments from pytest.main%0A%09%09argv_saved = list(sys.argv)%0A%09%09
+Invoke pytest, replacing argv.%0A%09%09%22%22%22%0A%09%09with _save_argv(_
 sys.
@@ -3197,13 +3197,13 @@
 rgv%5B
-1
 :
+1
 %5D 
-=
++
  sel
@@ -3211,17 +3211,20 @@
 .addopts
-%0A
+):%0A%09
 %09%09self.r
@@ -3240,22 +3240,36 @@
 e = 
+__import__('
 pytest
+')
 .main()%0A
 %09%09sy
@@ -3268,31 +3268,4 @@
 n()%0A
-%09%09sys.argv%5B:%5D = argv_saved%0A

Use contextlib to simplify run-tests.