test_util.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from youtube import util
  2. import settings
  3. import pytest # overview: https://realpython.com/pytest-python-testing/
  4. import urllib3
  5. import io
  6. import os
  7. import stem
  8. def load_test_page(name):
  9. with open(os.path.join('./tests/test_responses', name), 'rb') as f:
  10. return f.read()
  11. html429 = load_test_page('429.html')
  12. class MockResponse(urllib3.response.HTTPResponse):
  13. def __init__(self, body='success', headers=None, status=200, reason=''):
  14. print(body[0:10])
  15. headers = headers or {}
  16. if isinstance(body, str):
  17. body = body.encode('utf-8')
  18. self.body_io = io.BytesIO(body)
  19. self.read = self.body_io.read
  20. urllib3.response.HTTPResponse.__init__(
  21. self, body=body, headers=headers, status=status,
  22. preload_content=False, decode_content=False, reason=reason
  23. )
  24. class NewIdentityState():
  25. MAX_TRIES = util.TorManager.MAX_TRIES
  26. def __init__(self, new_identities_till_success):
  27. self.new_identities_till_success = new_identities_till_success
  28. def new_identity(self, *args, **kwargs):
  29. print('newidentity')
  30. self.new_identities_till_success -= 1
  31. def fetch_url_response(self, *args, **kwargs):
  32. cleanup_func = (lambda r: None)
  33. if self.new_identities_till_success == 0:
  34. return MockResponse(), cleanup_func
  35. return MockResponse(body=html429, status=429), cleanup_func
  36. class MockController():
  37. def authenticate(self, *args, **kwargs):
  38. pass
  39. @classmethod
  40. def from_port(cls, *args, **kwargs):
  41. return cls()
  42. def __enter__(self, *args, **kwargs):
  43. return self
  44. def __exit__(self, *args, **kwargs):
  45. pass
  46. @pytest.mark.parametrize('new_identities_till_success',
  47. [i for i in range(0, NewIdentityState.MAX_TRIES+2)])
  48. def test_exit_node_retry(monkeypatch, new_identities_till_success):
  49. new_identity_state = NewIdentityState(new_identities_till_success)
  50. # https://docs.pytest.org/en/stable/monkeypatch.html
  51. monkeypatch.setattr(settings, 'route_tor', 1)
  52. monkeypatch.setattr(util, 'tor_manager', util.TorManager()) # fresh one
  53. MockController.signal = new_identity_state.new_identity
  54. monkeypatch.setattr(stem.control, 'Controller', MockController)
  55. monkeypatch.setattr(util, 'fetch_url_response',
  56. new_identity_state.fetch_url_response)
  57. if new_identities_till_success <= NewIdentityState.MAX_TRIES:
  58. assert util.fetch_url('url') == b'success'
  59. else:
  60. with pytest.raises(util.FetchError) as excinfo:
  61. util.fetch_url('url')
  62. assert int(excinfo.value.code) == 429