Example #1
0
 def test_multipart(self):
     url = 'http://httpbin.org/post'
     data = '--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 68\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz--\r\n'
     headers = {
         'Content-Length': '495',
         'Content-Type': 'multipart/form-data; boundary=xXXxXXyYYzzz',
         'Accept': 'text/plain',
         'User-Agent': 'Mocket',
         'Accept-encoding': 'identity',
     }
     Entry.register(Entry.POST, url)
     response = requests.post(url, data=data, headers=headers)
     self.assertEqual(response.status_code, 200)
     last_request = Mocket.last_request()
     self.assertEqual(last_request.method, 'POST')
     self.assertEqual(last_request.path, '/post')
     self.assertEqual(last_request.body, data)
     sent_headers = dict(last_request.headers)
     self.assertEqualHeaders(
         sent_headers,
         {
             'accept': 'text/plain',
             'accept-encoding': 'identity',
             'content-length': '495',
             'content-type': 'multipart/form-data; boundary=xXXxXXyYYzzz',
             'host': 'httpbin.org',
             'user-agent': 'Mocket',
             'connection': 'keep-alive',
         }
     )
     self.assertEqual(len(Mocket._requests), 1)
Example #2
0
 def test_multipart(self):
     url = "http://httpbin.org/post"
     data = '--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 68\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz--\r\n'
     headers = {
         "Content-Length": "495",
         "Content-Type": "multipart/form-data; boundary=xXXxXXyYYzzz",
         "Accept": "text/plain",
         "User-Agent": "Mocket",
         "Accept-encoding": "identity",
     }
     Entry.register(Entry.POST, url)
     response = requests.post(url, data=data, headers=headers)
     self.assertEqual(response.status_code, 200)
     last_request = Mocket.last_request()
     self.assertEqual(last_request.method, "POST")
     self.assertEqual(last_request.path, "/post")
     self.assertEqual(last_request.body, data)
     sent_headers = dict(last_request.headers)
     self.assertEqualHeaders(
         sent_headers,
         {
             "accept": "text/plain",
             "accept-encoding": "identity",
             "content-length": "495",
             "content-type": "multipart/form-data; boundary=xXXxXXyYYzzz",
             "host": "httpbin.org",
             "user-agent": "Mocket",
             "connection": "keep-alive",
         },
     )
     self.assertEqual(len(Mocket._requests), 1)
Example #3
0
    def test_sockets(self):
        """
        https://github.com/mindflayer/python-mocket/issues/111
        https://gist.github.com/amotl/015ef6b336db55128798d7f1a9a67dea
        """

        # Define HTTP conversation.
        url = "http://127.0.0.1:8080/api/data"
        Entry.single_register(Entry.POST, url)

        # Define HTTP url segments and data.
        host = "127.0.0.1"
        port = 8080
        method = "POST"
        path = "/api/data"
        data = json.dumps({"hello": "world"})

        # Invoke HTTP request.
        address = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
        sock = socket.socket(address[0], address[1], address[2])

        sock.connect(address[-1])
        sock.write("%s %s HTTP/1.0\r\n" % (method, path))
        sock.write("Host: %s\r\n" % host)
        sock.write("Content-Type: application/json\r\n")
        sock.write("Content-Length: %d\r\n" % len(data))
        sock.write("Connection: close\r\n\r\n")
        sock.write(data)
        sock.close()

        # Proof that worked.
        self.assertEqual(Mocket.last_request().body, '{"hello": "world"}')
Example #4
0
 def test_set(self):
     Entry.register_response('SET mocket "is awesome!"', OK)
     self.assertTrue(self.rclient.set('mocket', 'is awesome!'))
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b'*3\r\n$3\r\nSET\r\n$6\r\nmocket\r\n$11\r\nis awesome!\r\n')
Example #5
0
 def test_multipart(self):
     url = 'http://httpbin.org/post'
     data = '--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 68\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz--\r\n'
     headers = {
         'Content-Length': '495',
         'Content-Type': 'multipart/form-data; boundary=xXXxXXyYYzzz',
         'Accept': 'text/plain',
         'User-Agent': 'Mocket',
         'Accept-encoding': 'identity',
     }
     Entry.register(Entry.POST, url)
     response = requests.post(url, data=data, headers=headers)
     self.assertEqual(response.status_code, 200)
     last_request = Mocket.last_request()
     self.assertEqual(last_request.method, 'POST')
     self.assertEqual(last_request.path, '/post')
     self.assertEqual(last_request.body, data)
     sent_headers = dict(last_request.headers)
     self.assertEqualHeaders(
         sent_headers, {
             'accept': 'text/plain',
             'accept-encoding': 'identity',
             'content-length': '495',
             'content-type': 'multipart/form-data; boundary=xXXxXXyYYzzz',
             'host': 'httpbin.org',
             'user-agent': 'Mocket',
             'connection': 'keep-alive',
         })
     self.assertEqual(len(Mocket._requests), 1)
Example #6
0
def test_uplink_system_temperature(network_lora, caplog):
    """
    Pretend to invoke the datalogger on a LoPy4 with basic system sensors.
    Effectively, only the "system.temperature" sensor will be transmitted
    over LoRa telemetry.

    By intercepting the lora socket communication, proof that the
    submitted payload is correct by checking the raw payload value
    and decoding it through Cayenne.
    """

    # Define artificial LoRa conversation.
    network_lora.register_conversation()

    # Invoke datalogger with LoRaWAN telemetry settings for a single duty cycle.
    from test.settings import telemetry_lorawan
    invoke_datalogger_pycom(caplog, settings=telemetry_lorawan)

    # Capture log output.
    captured = caplog.text

    # Proof it works by verifying log output.
    assert "Starting Terkin datalogger" in captured, captured
    assert "platform: LoPy4" in captured, captured
    assert "[LoRa] Starting LoRa Manager" in captured, captured
    assert "Telemetry transport: CayenneLPP over LoRaWAN/TTN" in captured, captured
    assert "Telemetry status: SUCCESS (1/1)" in captured, captured

    # Check the raw LoRa payload.
    from mocket import Mocket
    assert Mocket.last_request() == bytearray(b'\x00g\x01\xbf\x00\x01\x00')

    # Check the value after decoding from CayenneLPP.
    from cayennelpp import LppFrame
    data = LppFrame.from_bytes(Mocket.last_request()).data

    # System temperature
    assert data[0].channel == 0
    assert data[0].type == 103
    assert data[0].value == (44.7, )

    # EOF?
    assert data[1].channel == 0
    assert data[1].type == 1
    assert data[1].value == (0, )

    assert "[LoRa] No downlink message processed" in captured, captured
Example #7
0
 def test_set(self):
     Entry.register_response('SET mocket "is awesome!"', OK)
     self.assertTrue(self.rclient.set("mocket", "is awesome!"))
     self.assertEqual(len(Mocket.request_list()), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b"*3\r\n$3\r\nSET\r\n$6\r\nmocket\r\n$11\r\nis awesome!\r\n",
     )
Example #8
0
 def test_lrange(self):
     l = [b'one', b'two', b'three']
     Entry.register_response('LRANGE list 0 -1', l)
     self.assertEqual(self.rclient.lrange('list', 0, -1), l)
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b'*4\r\n$6\r\nLRANGE\r\n$4\r\nlist\r\n$1\r\n0\r\n$2\r\n-1\r\n')
Example #9
0
 def test_lrange(self):
     l = [b"one", b"two", b"three"]
     Entry.register_response("LRANGE list 0 -1", l)
     self.assertEqual(self.rclient.lrange("list", 0, -1), l)
     self.assertEqual(len(Mocket.request_list()), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b"*4\r\n$6\r\nLRANGE\r\n$4\r\nlist\r\n$1\r\n0\r\n$2\r\n-1\r\n",
     )
Example #10
0
    def test_request_bodies(self):
        url = 'http://bit.ly/fakeurl/{0}'

        for e in range(5):
            u = url.format(e)
            Entry.single_register(Entry.POST, u, body=str(e))
            request_body = urlencode({'key-{0}'.format(e): 'value={0}'.format(e)})
            urlopen(u, request_body.encode('utf-8'))
            last_request = Mocket.last_request()
            assert last_request.body == request_body
Example #11
0
    def test_request_bodies(self):
        url = "http://bit.ly/fakeurl/{0}"

        for e in range(5):
            u = url.format(e)
            Entry.single_register(Entry.POST, u, body=str(e))
            request_body = urlencode({"key-{0}".format(e): "value={0}".format(e)})
            urlopen(u, request_body.encode("utf-8"))
            last_request = Mocket.last_request()
            assert last_request.body == request_body
Example #12
0
 def test_err(self):
     Entry.register_response(
         'INCRBY counter one',
         ERROR('ERR value is not an integer or out of range'))
     self.assertRaises(redis.ResponseError, self.rclient.incr, 'counter',
                       'one')
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b'*3\r\n$6\r\nINCRBY\r\n$7\r\ncounter\r\n$3\r\none\r\n')
Example #13
0
    def test_collect_last_request(self):
        addr = ("localhost", 80)

        entry = MocketEntry(addr, True)
        Mocket.register(entry)
        with Mocketizer():
            _so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            _so.connect(addr)
            _so.sendall(b"data\r\n")
            _so.close()
            self.assertEqual(Mocket.last_request(), b"data\r\n")
Example #14
0
 def test_err(self):
     Entry.register_response(
         "INCRBY counter one",
         ERROR("ERR value is not an integer or out of range"))
     self.assertRaises(redis.ResponseError, self.rclient.incr, "counter",
                       "one")
     self.assertEqual(len(Mocket.request_list()), 1)
     self.assertEqual(
         Mocket.last_request().data,
         b"*3\r\n$6\r\nINCRBY\r\n$7\r\ncounter\r\n$3\r\none\r\n",
     )
Example #15
0
 def test_mockhttp_entry_collect_duplicates(self):
     Entry.single_register(
         Entry.POST, "http://testme.org/", status=200, match_querystring=False
     )
     requests.post(
         "http://testme.org/?foo=bar",
         data="{'foo': 'bar'}",
         headers={"content-type": "application/json"},
     )
     requests.post("http://testme.org/")
     self.assertEqual(len(Mocket._requests), 2)
     self.assertEqual(Mocket.last_request().path, "/")
Example #16
0
def test_mocket_cpython_requests():
    """
    Using the ``requests`` module works perfectly.
    """

    # Define HTTP request details.
    url = 'http://127.0.0.1/api/data'
    data = {'hello': 'world'}

    # Mock HTTP conversation.
    Entry.single_register(Entry.POST, url)

    # Invoke HTTP request.
    requests.post(url, json=data)

    # Proof that worked.
    assert Mocket.last_request().body == json.dumps(data)
Example #17
0
def test_mocket_socket():
    """
    Demonstrate HTTP streaming to Mocket's "mockhttp".

    The error is::

        self = <mocket.mockhttp.Request object at 0x108cf74c0>, data = b'POST /api/data HTTP/1.0\r\n'

            def __init__(self, data):
        >       _, self.body = decode_from_bytes(data).split('\r\n\r\n', 1)
        E       ValueError: not enough values to unpack (expected 2, got 1)

        .venv3/lib/python3.8/site-packages/mocket/mockhttp.py:23: ValueError

    The reason is that ``data`` is essentially::

        b'POST /api/data HTTP/1.0\r\n'

    which well fails on being split by ``\r\n\r\n`` appropriately.
    So, when receiving a streamed response, Mocket's "mockhttp"
    should not expect the data to be sent en bloc.
    """

    # Define HTTP request details.
    method = 'POST'
    url = 'http://127.0.0.1/api/data'
    data = {'hello': 'world'}

    # Mock HTTP conversation.
    Entry.single_register(Entry.POST, url)

    # Invoke HTTP request.
    send_request(url, method, json=data)

    # Proof that worked.
    assert Mocket.last_request().body == json.dumps(data)
Example #18
0
def test_uplink_environmental_sensors(mocker, network_lora, caplog):
    """
    Pretend to invoke the datalogger on a LoPy4 with environmental sensors.

    By intercepting the lora socket communication, proof that the
    submitted payload is correct by checking the raw payload value
    and decoding it through Cayenne.
    """

    # Define artificial LoRa conversation.
    network_lora.register_conversation()

    # Mix together different settings.
    from test.settings import telemetry_lorawan
    from test.settings import sensors as sensor_settings
    mocker.patch('test.settings.telemetry_lorawan.sensors',
                 sensor_settings.sensors)

    # Invoke datalogger with LoRaWAN telemetry settings for a single duty cycle.
    invoke_datalogger_pycom(caplog, settings=telemetry_lorawan)

    # Capture log output.
    captured = caplog.text

    # Proof it works by verifying log output.
    assert "Starting Terkin datalogger" in captured, captured
    assert "platform: LoPy4" in captured, captured
    assert "[LoRa] Starting LoRa Manager" in captured, captured
    assert "Telemetry transport: CayenneLPP over LoRaWAN/TTN" in captured, captured
    assert "Telemetry status: SUCCESS (1/1)" in captured, captured

    # Check the raw LoRa payload.
    from mocket import Mocket
    assert Mocket.last_request() == bytearray(
        b'\x00g\x01\xbf\x00\x03\x01\xa4\x00\x02\x01\x80\x01g\x01\xe1\x02g\x01\xe1'
        b'\x03g\x00\x97\x00s)7\x00h\x9b\x00\x01\x00')

    # Check the value after decoding from CayenneLPP.
    from cayennelpp import LppFrame
    data = LppFrame.from_bytes(Mocket.last_request()).data

    # System temperature
    assert data[0].channel == 0
    assert data[0].type == 103
    assert data[0].value == (44.7, )

    # Voltage
    assert data[1].channel == 0
    assert data[1].type == 3
    assert data[1].value == (4.2, )

    # Weight (kg)
    assert data[2].channel == 0
    assert data[2].type == 2
    assert data[2].value == (3.84, )

    # DS18B20 temperature
    assert data[3].channel == 1
    assert data[3].type == 103
    assert data[3].value == (48.1, )
    assert data[4].channel == 2
    assert data[4].type == 103
    assert data[4].value == (48.1, )

    # BME280 temperature
    assert data[5].channel == 3
    assert data[5].type == 103
    assert data[5].value == (15.1, )

    # BME280 pressure
    assert data[6].channel == 0
    assert data[6].type == 115
    assert data[6].value == (1055.1, )

    # BME280 humidity
    assert data[7].channel == 0
    assert data[7].type == 104
    assert data[7].value == (77.5, )

    # EOF?
    assert data[8].channel == 0
    assert data[8].type == 1
    assert data[8].value == (0, )

    assert "[LoRa] No downlink message processed" in captured, captured
Example #19
0
 def test_set(self):
     Entry.register_response('SET mocket "is awesome!"', OK)
     self.assertTrue(self.rclient.set('mocket', 'is awesome!'))
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(Mocket.last_request().data, b'*3\r\n$3\r\nSET\r\n$6\r\nmocket\r\n$11\r\nis awesome!\r\n')
Example #20
0
 def test_get_unicode(self):
     Entry.register_response('GET snowman', '\u2603')
     self.assertEqual(self.rclient.get('snowman'), b'\xe2\x98\x83')
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(Mocket.last_request().data, b'*2\r\n$3\r\nGET\r\n$7\r\nsnowman\r\n')
Example #21
0
 def test_lrange(self):
     l = [b'one', b'two', b'three']
     Entry.register_response('LRANGE list 0 -1', l)
     self.assertEqual(self.rclient.lrange('list', 0, -1), l)
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(Mocket.last_request().data, b'*4\r\n$6\r\nLRANGE\r\n$4\r\nlist\r\n$1\r\n0\r\n$2\r\n-1\r\n')
Example #22
0
 def test_err(self):
     Entry.register_response('INCRBY counter one', ERROR('ERR value is not an integer or out of range'))
     self.assertRaises(redis.ResponseError, self.rclient.incr, 'counter', 'one')
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(Mocket.last_request().data, b'*3\r\n$6\r\nINCRBY\r\n$7\r\ncounter\r\n$3\r\none\r\n')
Example #23
0
 def test_get_unicode(self):
     Entry.register_response("GET snowman", "\u2603")
     self.assertEqual(self.rclient.get("snowman"), b"\xe2\x98\x83")
     self.assertEqual(len(Mocket.request_list()), 1)
     self.assertEqual(Mocket.last_request().data,
                      b"*2\r\n$3\r\nGET\r\n$7\r\nsnowman\r\n")
Example #24
0
 def test_get_unicode(self):
     Entry.register_response('GET snowman', '\u2603')
     self.assertEqual(self.rclient.get('snowman'), b'\xe2\x98\x83')
     self.assertEqual(len(Mocket._requests), 1)
     self.assertEqual(Mocket.last_request().data, b'*2\r\n$3\r\nGET\r\n$7\r\nsnowman\r\n')
Example #25
0
 def __getattr__(self, name):
     if name == "last_request":
         return Mocket.last_request()
     if name == "latest_requests":
         return Mocket.request_list()
     return getattr(Entry, name)
Example #26
0
 def test_collect(self):
     request = 'GET /get/p/?b=2&a=1 HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: testme.org\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
     Mocket.collect(request)
     self.assertEqual(Mocket.last_request(), request)
     self.assertEqual(Mocket._requests, [request])
Example #27
0
 def test_lastrequest(self):
     self.assertEqual(Mocket.last_request(), None)
     Mocket._requests.extend([1, 2, 3])
     self.assertEqual(Mocket.last_request(), 3)
Example #28
0
 def test_collect(self):
     request = 'GET /get/p/?b=2&a=1 HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: testme.org\r\nConnection: close\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
     Mocket.collect(request)
     self.assertEqual(Mocket.last_request(), request)
     self.assertEqual(Mocket._requests, [request])
Example #29
0
 def test_lastrequest(self):
     self.assertEqual(Mocket.last_request(), None)
     Mocket._requests.extend([1, 2, 3])
     self.assertEqual(Mocket.last_request(), 3)