Python
pyDoubles v1.2 released! Hamcrest compatibility
8 Jul 11
cars_finder = stub(CarFinder())
when(cars_finder.count_by_brand).with_args(
equal_to_ignoring_case(“bmw”)).then_return(120)
Hamcrest comes with a library of useful matchers. Here are some of the most important ones:
- Core
- anything – always matches, useful if you don’t care what the object under test is
- describedAs – decorator to adding custom failure description
- is – decorator to improve readability – see “Sugar”, below
- Logical
- allOf – matches if all matchers match, short circuits (like Java &&)
- anyOf – matches if any matchers match, short circuits (like Java ||)
- not – matches if the wrapped matcher doesn’t match and vice versa
- Object
- equalTo – test object equality using Object.equals
- hasToString – test Object.toString
- instanceOf, isCompatibleType – test type
- notNullValue, nullValue – test for null
- sameInstance – test object identity
- Beans
- hasProperty – test JavaBeans properties
- Collections
- array – test an array’s elements against an array of matchers
- hasEntry, hasKey, hasValue – test a map contains an entry, key or value
- hasItem, hasItems – test a collection contains elements
- hasItemInArray – test an array contains an element
- Number
- closeTo – test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo – test ordering
- Text
- equalToIgnoringCase – test string equality ignoring case
- equalToIgnoringWhiteSpace – test string equality ignoring differences in runs of whitespace
- containsString, endsWith, startsWith – test string matching
- A method called “matches” that returns a boolean value and it receives a parameter to be checked.
- Optionally, a constructor who gets what you need to make the match.
- Optionally, define value to “matcher_name” which prints a descriptive message of your matches in pyDoubles messages.
class IsTelephoneNumber(PyDoublesMatcher):
matcher_name = "is telephone number"
def __init__(self, format):
self.defined_arg = format
def matches(self, arg):
return self._is_telephone_number_in_format(arg, self.defined_arg)
def _is_telephone_number_in_format(self, telephone, format):
.... assume this would implement some check...
With a little more work, you can support your matcher with pyDoubles and Hamcrest. You can find more information in the Hamcrest wiki.
The currently supported version of PyHamcrest is v1.5.
Finally, the method: “assert_that” as been renamed to “assert_that_method” to avoid conflicts with Hamcrest.
You can download the latest version of pyDoubles here: https://bitbucket.org/carlosble/pydoubles/downloads/
Realiza peticiones web http o https con Python
17 Dec 10
Como muchas tareas en python, realizar peticiones web a una url es muy sencillo. Sólo tienes que usar la clase HTTPConnection o HTTPSConnection que se encuentra en el módulo httplib, dependiendo de si es una petición http o https.
Ejemplo de una petición POST a la url https://www.paypal.com/nvp/:
import httplib, urllib
connection = httplib.HTTPSConnection("www.paypal.com")
params = urllib.urlencode({"USER":"usuario",
"PWD":"12345"})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
connection.request("POST", "/nvp", params, headers)
response = connection.getresponse()
data = response.read()
connection.close()
La petición comienza al llamar al método request pasándole el tipo de petición (POST, GET, HEAD, PUT), la página de la petición, los parámetros y las cabezeras. Los parámetros y las cabeceras son opciones. La cabezera “Content-length” la añade automáticamente python.
Para obtener la respuesta debemos de obtener el objeto HTTPResponse llamando al método getresponse() de la conexión que contiene toda la información referente a la respuesta. Desde este objeto podremos obtener el string de la respuesta de la petición.
El método urlencode te permitirá formatear la cadena de parámetros de una forma sencilla, despreocupándote de concatenarlos y codificarlos.
Un ejemplo de una petición GET:
import httplib
connection = httplib.HTTPConnection("www.rubenbernardez.com")
connection.request("GET","/blog/")
response = connection.getresponse()
data = response.read()
connection.close()