如果使用HTTP / 1.1,模拟S3服务器会停止

时间:2018-03-17 20:01:24

标签: python testing boto3 awss3transfermanager

我正在编写一个测试,其中使用http.server.HTTPServer / http.server.BaseHTTPRequestHandler在测试环境中加载一个简单的模拟S3,以测试涉及Boto的S3Transfer的多部分下载行为。 / p>

除非我指定服务器使用HTTP/1.1,否则它可以正常工作。在这种情况下,它将下载2个8mb部分的100mb文件,然后挂起。我希望模拟服务器使用HTTP/1.1,因为那是真正的S3使用的(我相信)。

下面是测试的简化版本,可以通过......运行。

pip3 install boto3
python3 test.py    
# test.py

import http.server
import re
import threading

import boto3
from botocore import (
    UNSIGNED,
)
from botocore.client import (
    Config,
)

length = 100 * 2**20

class MockS3(http.server.BaseHTTPRequestHandler):
    # If the below line is commented, the download completes
    protocol_version = 'HTTP/1.1'

    def do_GET(self):
        range_header = self.headers['Range']
        match = re.search(r'^bytes=(\d+)-(\d*)', range_header)
        start_inclusive_str, end_inclusive_str = match.group(1), match.group(2)
        start = int(start_inclusive_str)
        end = int(end_inclusive_str) + 1 if end_inclusive_str else length
        bytes_to_send = end - start

        self.send_response(206)
        self.send_header('Content-Length', str(bytes_to_send))
        self.end_headers()
        self.wfile.write(bytearray(bytes_to_send))

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-Length', length)
        self.end_headers()

server_address = ('localhost', 5678)
server = http.server.HTTPServer(server_address, MockS3)
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()

class Writable():
    def write(self, data):
        pass

s3_client = boto3.client('s3',
  endpoint_url='http://localhost:5678',
  config=Config(signature_version=UNSIGNED),
)

s3_client.download_fileobj(
  Bucket='some',
  Key='key',
  Fileobj=Writable(),
)

请注意,Writable故意可搜索:在我的真实代码中,我使用了不可搜索的文件类对象。

是的,moto 可以用来制作一个模拟S3,我这样做是为了进行其他测试,但对于这个特定的测试,我希望"真实&#34 ;服务器。涉及自定义文件对象,并且希望确保S3Transfer和其他与此问题无关的代码按照我的预期一起运行。

如何设置使用HTTP/1.1且S3Transfer可以从中下载的模拟S3服务器?

1 个答案:

答案 0 :(得分:1)

您的线程逻辑中存在错误。您当前正在做的是在单独的线程上提供服务,但您真正想要做的是同时处理多个线程上的请求。

这可以通过创建一个仅仅混合了线程功能的非常愚蠢的 HTTP服务器来实现:

class ThreadingServer(ThreadingMixIn, HTTPServer):
    pass

并从此服务器而不是基座HTTPServer提供服务。

至于为什么这适用于HTTP/1.0,连接在服务单个请求后关闭。