From a796971fc949106406a064b24dbbf9111e91a926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Falc=C3=A3o?= Date: Tue, 8 Feb 2011 00:31:26 -0200 Subject: [PATCH] raising exception when the developer register a content-length bigger than actual body size. closes #1 --- httpretty/__init__.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/httpretty/__init__.py b/httpretty/__init__.py index 6529a02..202ae4c 100644 --- a/httpretty/__init__.py +++ b/httpretty/__init__.py @@ -25,6 +25,7 @@ # OTHER DEALINGS IN THE SOFTWARE. import re import socket +import warnings from datetime import datetime from StringIO import StringIO @@ -43,6 +44,9 @@ try: except ImportError: socks = None +class HTTPrettyError(Exception): + pass + class FakeSockFile(StringIO): def read(self, amount=None): amount = amount or self.len @@ -194,6 +198,7 @@ class Entry(object): self.method = method self.uri = uri self.body = body + self.body_length = len(body or '') self.adding_headers = adding_headers or {} self.forcing_headers = forcing_headers or {} self.status = int(status) @@ -202,6 +207,30 @@ class Entry(object): name = "-".join(k.split("_")).capitalize() self.adding_headers[name] = v + self.validate() + + def validate(self): + content_length_keys = 'Content-Length', 'content-cength' + for key in content_length_keys: + got = self.adding_headers.get(key, self.forcing_headers.get(key, None)) + if got is None: + continue + + try: + igot = int(got) + except ValueError: + warnings.warn('HTTPretty got to register the Content-Length header with "%r" which is not a number' % got) + + if igot > self.body_length: + raise HTTPrettyError( + 'HTTPretty got inconsistent parameters. The header Content-Length you registered expects size "%d" ' + 'but the body you registered for that has actually length "%d".\n' + 'Fix that, or if you really want that, call register_uri with "fill_with" callback.' % ( + igot, self.body_length + ) + ) + + def __repr__(self): return r'' % (self.method, self.uri, self.status)