#!/usr/bin/env python3
"""wcs/net.py: every requests call without a timeout gets the default one, an explicit one stays (W7)."""
import os
import sys
import types
import unittest

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, ROOT)

from wcs import net  # noqa: E402


class Session(object):
    def request(self, method, url, **kwargs):
        return kwargs.get('timeout')


class NetTests(unittest.TestCase):
    def setUp(self):
        self.module = types.ModuleType('requests.sessions')
        self.module.Session = type('Session', (Session,), {})

    def test_a_call_without_timeout_gets_the_default(self):
        net._patch(self.module)
        session = self.module.Session()
        self.assertEqual(session.request('GET', 'https://x'), net.DEFAULT_TIMEOUT)
        self.assertEqual(session.request('GET', 'https://x', timeout=None), net.DEFAULT_TIMEOUT)

    def test_an_explicit_timeout_stays(self):
        net._patch(self.module)
        self.assertEqual(self.module.Session().request('GET', 'https://x', timeout=3), 3)

    def test_patching_twice_wraps_once(self):
        net._patch(self.module)
        first = self.module.Session.request
        net._patch(self.module)
        self.assertIs(self.module.Session.request, first)

    def test_install_adds_one_finder_and_never_raises(self):
        before = [f for f in sys.meta_path if getattr(f, 'milionar_timeout', False)]
        net.install()
        net.install()
        after = [f for f in sys.meta_path if getattr(f, 'milionar_timeout', False)]
        self.assertEqual(len(after), max(1, len(before)))
        for finder in after:
            sys.meta_path.remove(finder)


if __name__ == '__main__':
    unittest.main(verbosity=1)
