# Path: tests/testlib/testcase_with_tmpdir.py
# class TestCase(unittest.TestCase):
#     """Adds setUpClass an tearDownClass that create and destroy tmpdir."""
# 
#     _tmpdir = None
# 
#     @classmethod
#     def setUpClass(cls):
#         """Create tmp dir to write to and check."""
#         cls._tmpdir = tempfile.mkdtemp()
#         if (not os.path.isdir(cls._tmpdir)):
#             raise Exception("Failed to create tempdir to use for dump tests")
#         try:
#             cls.extraSetUpClass()
#         except Exception:
#             pass
# 
#     @classmethod
#     def tearDownClass(cls):
#         """Cleanup."""
#         if (not os.path.isdir(cls._tmpdir)):
#             raise Exception("Ooops, no tempdir (%s) to clean up?" % (cls._tmpdir))
#         shutil.rmtree(cls._tmpdir)
#         try:
#             cls.extraTearUpClass()
#         except Exception:
#             pass
# 
#     @property
#     def tmpdir(self):
#         """Read-only access to _tmpdir, just in case... The rmtree scares me."""
#         return(self._tmpdir)
# 
# Path: tests/testlib/webserver_context.py
# @contextlib.contextmanager
# def webserver(dir='/tmp/htdocs', host='localhost', port=9999):
#     """Context Manager that provides a webserver serving files from dir."""
#     p = Process(target=run_webserver, args=(dir, host, port))
#     p.start()
#     # Wait for the server to be launched
#     base_url = 'http://%s:%d/' % (host, port)
#     for j in range(0, 10):
#         try:
#             requests.get(base_url, timeout=0.1)
#             break
#         except requests.exceptions.ConnectionError:
#             pass
#         time.sleep(0.1)
#     else:
#         print("Failed to start test webserver from %s at host=%s port=%d" % (dir, host, port))
#     # Setup complete, yield to execute with clause
#     try:
#         yield
#     finally:
#         # Close the server
#         p.terminate()
#         time.sleep(0.1)
# 
# Path: resync/url_or_file_open.py
# NUM_REQUESTS = 0
# 
# CONFIG = {
#     'bearer_token': None,
#     'delay': None,
#     'user_agent': 'resync/' + __version__
# }
# 
# def set_url_or_file_open_config(key, value):
#     """Set the global config."""
#     global CONFIG
#     CONFIG[key] = value
# 
# def url_or_file_open(uri, method=None, timeout=None):
#     """Wrapper around urlopen() to prepend file: if no scheme provided.
# 
#     Can be used as a context manager because the return value from urlopen(...)
#     supports both that and straightforwrd use as simple file handle object.
# 
#     If timeout is exceeded then urlopen(..) will raise a socket.timeout exception. If
#     no timeout is specified then the global default will be used.
#     """
#     if (not re.match(r'''\w+:''', uri)):
#         uri = 'file:' + uri
#     headers = {'User-Agent': CONFIG['user_agent']}
#     # Do we need to send an Authorization header?
#     # FIXME - This token will be added blindy to all requests. This is insecure
#     # if the --noauth setting is used allowing requests across different domains.
#     # It would be better to have some scheme where a token is tied to a particular
#     # domain, or domain pattern.
#     if CONFIG['bearer_token'] is not None:
#         headers['Authorization'] = 'Bearer ' + CONFIG['bearer_token']
#     # Have we got a delay set? Apply only to web requests after first
#     global NUM_REQUESTS
#     if NUM_REQUESTS != 0 and CONFIG['delay'] is not None and not uri.startswith('file:'):
#         time.sleep(CONFIG['delay'])
#     NUM_REQUESTS += 1
#     maybe_timeout = {} if timeout is None else {'timeout': timeout}
#     return urlopen(Request(url=uri, headers=headers, method=method), **maybe_timeout)


from .testlib import TestCase, webserver
from resync.url_or_file_open import NUM_REQUESTS, CONFIG, set_url_or_file_open_config, url_or_file_open
import time
"""Tests for resync.url_or_file_open."""



class TestUrlOrFileOpen(TestCase):

    def test_set_url_or_file_open_config(self):
        """Test set_url_or_file_open_config function."""
        self.assertEqual(CONFIG['bearer_token'], None)
        self.assertEqual(CONFIG['delay'], None)
        self.assertNotIn('my_thing', CONFIG)
        set_url_or_file_open_config('bearer_token', 'open seasame')
        self.assertEqual(CONFIG['bearer_token'], 'open seasame')
        set_url_or_file_open_config('my_thing', 'special')
        self.assertEqual(CONFIG['my_thing'], 'special')

    def test_url_or_file_open(self):
        """Test basic operation of url_or_file_open function."""
        # Open file
        fh = url_or_file_open('tests/testdata/dir1/file_a')
        self.assertIn(b'I am file a', fh.read())
        fh.close()
        with url_or_file_open('file:tests/testdata/dir1/file_b') as fh:
            self.assertIn(b'I am file b', fh.read())
        # Open URL
        with webserver('tests/testdata', 'localhost', 9999):
            with url_or_file_open('http://localhost:9999/dir2/file_x') as fh:
                self.assertIn(b'I am the mysterious file_x', fh.read())
            # test delay of 0.1s

# Path: tests/testlib/testcase_with_tmpdir.py
# class TestCase(unittest.TestCase):
#     """Adds setUpClass an tearDownClass that create and destroy tmpdir."""
# 
#     _tmpdir = None
# 
#     @classmethod
#     def setUpClass(cls):
#         """Create tmp dir to write to and check."""
#         cls._tmpdir = tempfile.mkdtemp()
#         if (not os.path.isdir(cls._tmpdir)):
#             raise Exception("Failed to create tempdir to use for dump tests")
#         try:
#             cls.extraSetUpClass()
#         except Exception:
#             pass
# 
#     @classmethod
#     def tearDownClass(cls):
#         """Cleanup."""
#         if (not os.path.isdir(cls._tmpdir)):
#             raise Exception("Ooops, no tempdir (%s) to clean up?" % (cls._tmpdir))
#         shutil.rmtree(cls._tmpdir)
#         try:
#             cls.extraTearUpClass()
#         except Exception:
#             pass
# 
#     @property
#     def tmpdir(self):
#         """Read-only access to _tmpdir, just in case... The rmtree scares me."""
#         return(self._tmpdir)
# 
# Path: tests/testlib/webserver_context.py
# @contextlib.contextmanager
# def webserver(dir='/tmp/htdocs', host='localhost', port=9999):
#     """Context Manager that provides a webserver serving files from dir."""
#     p = Process(target=run_webserver, args=(dir, host, port))
#     p.start()
#     # Wait for the server to be launched
#     base_url = 'http://%s:%d/' % (host, port)
#     for j in range(0, 10):
#         try:
#             requests.get(base_url, timeout=0.1)
#             break
#         except requests.exceptions.ConnectionError:
#             pass
#         time.sleep(0.1)
#     else:
#         print("Failed to start test webserver from %s at host=%s port=%d" % (dir, host, port))
#     # Setup complete, yield to execute with clause
#     try:
#         yield
#     finally:
#         # Close the server
#         p.terminate()
#         time.sleep(0.1)
# 
# Path: resync/url_or_file_open.py
# NUM_REQUESTS = 0
# 
# CONFIG = {
#     'bearer_token': None,
#     'delay': None,
#     'user_agent': 'resync/' + __version__
# }
# 
# def set_url_or_file_open_config(key, value):
#     """Set the global config."""
#     global CONFIG
#     CONFIG[key] = value
# 
# def url_or_file_open(uri, method=None, timeout=None):
#     """Wrapper around urlopen() to prepend file: if no scheme provided.
# 
#     Can be used as a context manager because the return value from urlopen(...)
#     supports both that and straightforwrd use as simple file handle object.
# 
#     If timeout is exceeded then urlopen(..) will raise a socket.timeout exception. If
#     no timeout is specified then the global default will be used.
#     """
#     if (not re.match(r'''\w+:''', uri)):
#         uri = 'file:' + uri
#     headers = {'User-Agent': CONFIG['user_agent']}
#     # Do we need to send an Authorization header?
#     # FIXME - This token will be added blindy to all requests. This is insecure
#     # if the --noauth setting is used allowing requests across different domains.
#     # It would be better to have some scheme where a token is tied to a particular
#     # domain, or domain pattern.
#     if CONFIG['bearer_token'] is not None:
#         headers['Authorization'] = 'Bearer ' + CONFIG['bearer_token']
#     # Have we got a delay set? Apply only to web requests after first
#     global NUM_REQUESTS
#     if NUM_REQUESTS != 0 and CONFIG['delay'] is not None and not uri.startswith('file:'):
#         time.sleep(CONFIG['delay'])
#     NUM_REQUESTS += 1
#     maybe_timeout = {} if timeout is None else {'timeout': timeout}
#     return urlopen(Request(url=uri, headers=headers, method=method), **maybe_timeout)


# Path: tests/test_url_or_file_open.py
from .testlib import TestCase, webserver
from resync.url_or_file_open import NUM_REQUESTS, CONFIG, set_url_or_file_open_config, url_or_file_open
import time

"""Tests for resync.url_or_file_open."""



class TestUrlOrFileOpen(TestCase):

    def test_set_url_or_file_open_config(self):
        """Test set_url_or_file_open_config function."""
        self.assertEqual(CONFIG['bearer_token'], None)
        self.assertEqual(CONFIG['delay'], None)
        self.assertNotIn('my_thing', CONFIG)
        set_url_or_file_open_config('bearer_token', 'open seasame')
        self.assertEqual(CONFIG['bearer_token'], 'open seasame')
        set_url_or_file_open_config('my_thing', 'special')
        self.assertEqual(CONFIG['my_thing'], 'special')

    def test_url_or_file_open(self):
        """Test basic operation of url_or_file_open function."""
        # Open file
        fh = url_or_file_open('tests/testdata/dir1/file_a')
        self.assertIn(b'I am file a', fh.read())
        fh.close()
        with url_or_file_open('file:tests/testdata/dir1/file_b') as fh:
            self.assertIn(b'I am file b', fh.read())
        # Open URL
        with webserver('tests/testdata', 'localhost', 9999):
            with url_or_file_open('http://localhost:9999/dir2/file_x') as fh:
                self.assertIn(b'I am the mysterious file_x', fh.read())
            # test delay of 0.1s

            set_url_or_file_open_config('delay', 0.1)