Skip to content
Myr

test_keep_alive.py

This file

Path

tests/test_keep_alive.py

65 lines · 2.1 KiB · Python

Last changed by

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption12aa401

History of this file

Take it

1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5import sys
6import unittest
7
8# Path hack.
9sys.path.insert(0, os.path.abspath('..'))
10import requests
11import dummy_server
12
13class KeepAliveTests(unittest.TestCase):
14    server_and_proxy_port = 1234
15    request_count = 2
16    url = 'http://localhost:{0}'.format(server_and_proxy_port)
17    proxies={'http': url}
18
19    def setUp(self):
20        self.session = requests.session()
21        self.proxy_server = dummy_server.HttpServer(self.server_and_proxy_port)
22        self.proxy_server.start()
23
24    def tearDown(self):
25        self.proxy_server.close()
26
27    def test_keep_alive_with_direct_connection(self):
28        self.make_requests()
29        self.check_each_request_are_in_same_connection()
30
31    def test_no_keep_alive_with_direct_connection(self):
32        self.disable_keep_alive_in_session()
33        self.make_requests()
34        self.check_each_request_are_in_different_connection()
35
36    def test_keep_alive_with_proxy_connection(self):
37        self.make_proxy_requests()
38        self.check_each_request_are_in_same_connection()
39
40    def test_no_keep_alive_with_proxy_connection(self):
41        self.disable_keep_alive_in_session()
42        self.make_proxy_requests()
43        self.check_each_request_are_in_different_connection()
44
45    def make_proxy_requests(self):
46        self.make_requests(self.proxies)
47
48    def make_requests(self, proxies=None):
49        for _ in range(self.request_count):50            self.session.get(self.url, proxies=proxies).text
51
52    def check_each_request_are_in_same_connection(self):
53        """Keep-alive requests open a single connection to the server."""
54        self.assertEqual(self.proxy_server.connection_count, 1)
55
56    def check_each_request_are_in_different_connection(self):
57        """Keep-alive requests open a single connection to the server."""
58        self.assertEqual(self.proxy_server.connection_count, self.request_count)
59
60    def disable_keep_alive_in_session(self):
61        self.session.config['keep_alive'] = False
62
63
64if __name__ == '__main__':
65    unittest.main()