from unittest import TestCase

from tornado.testing import AsyncTestCase, gen_test

from tornado_stub_client import AsyncHTTPStubClient, reset, stub


class IntegrationTest(AsyncTestCase, TestCase):
    def setUp(self):
        super().setUp()
        reset()

    @gen_test
    def test_stub_and_fetch(self):
        client = AsyncHTTPStubClient()
        stub("/hello").and_return(body=b"world")
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"world")

    @gen_test
    def test_can_fetch_twice(self):
        client = AsyncHTTPStubClient()
        stub("/hello").and_return(body=b"world")
        yield client.fetch("/hello")
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"world")

    @gen_test
    def test_can_queue_stub_responses(self):
        client = AsyncHTTPStubClient()
        stub("/hello").and_return(body=b"hello").and_return(
            body=b"beautiful"
        ).and_return(body=b"world")

        # First Response
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"hello")

        # Second Response
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"beautiful")

        # Third Response
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"world")

        # Fourth Response
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, b"hello")

    @gen_test
    def test_with_syntax(self):
        client = AsyncHTTPStubClient()
        with stub("/hello").and_return(body=b"world"):
            response = yield client.fetch("/hello")
            self.assertEqual(response.code, 200)
            self.assertEqual(response.body, b"world")
        response = yield client.fetch("/hello")
        self.assertEqual(response.code, 404)
