Exemple #1
0
def test_get_https_text():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(response)
    pool.socket.return_value = sock
    ssl = mocket.SSLContext()

    s = adafruit_requests.Session(pool, ssl)
    r = s.get("https://" + host + path)

    sock.connect.assert_called_once_with((host, 443))

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])
    assert r.text == str(text, "utf-8")

    # Close isn't needed but can be called to release the socket early.
    r.close()
Exemple #2
0
def do_test_get_text(extra=b""):
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)),)
    c = _chunk(text, 33, extra)
    print(c)
    sock = mocket.Mocket(headers + c)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    r = s.get("http://" + host + path)

    sock.connect.assert_called_once_with((ip, 80))

    sock.send.assert_has_calls(
        [
            mock.call(b"GET"),
            mock.call(b" /"),
            mock.call(b"testwifi/index.html"),
            mock.call(b" HTTP/1.1\r\n"),
        ]
    )
    sock.send.assert_has_calls(
        [
            mock.call(b"Host: "),
            mock.call(b"wifitest.adafruit.com"),
        ]
    )
    assert r.text == str(text, "utf-8")
Exemple #3
0
def do_test_close_flush(extra=b""):
    """Test that a chunked response can be closed even when the request contents were not accessed."""
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)),)
    c = _chunk(text, 33, extra)
    print(c)
    sock = mocket.Mocket(headers + c)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    r = s.get("http://" + host + path)

    sock.connect.assert_called_once_with((ip, 80))

    sock.send.assert_has_calls(
        [
            mock.call(b"GET"),
            mock.call(b" /"),
            mock.call(b"testwifi/index.html"),
            mock.call(b" HTTP/1.1\r\n"),
        ]
    )
    sock.send.assert_has_calls(
        [
            mock.call(b"Host: "),
            mock.call(b"wifitest.adafruit.com"),
        ]
    )

    r.close()
def test_second_send_fails():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(response + response)
    pool.socket.return_value = sock
    ssl = mocket.SSLContext()

    s = adafruit_requests.Session(pool, ssl)
    r = s.get("https://" + host + path)

    sock.send.assert_has_calls([
        mock.call(b"testwifi/index.html"),
    ])

    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
        mock.call(b"\r\n"),
    ])
    assert r.text == str(text, "utf-8")

    sock.send.side_effect = None
    sock.send.return_value = 0

    with pytest.raises(RuntimeError):
        s.get("https://" + host + path + "2")

    sock.connect.assert_called_once_with((host, 443))
    # Make sure that the socket is closed after send fails.
    sock.close.assert_called_once()
    pool.socket.assert_called_once()
Exemple #5
0
def main() -> None:
    print("Connecting to %s" % SSID_NAME)
    try:
        wifi.radio.connect(SSID_NAME, SSID_PSW)
    except:
        magtag.exit_and_deep_sleep(2)
    print("Connected to %s!" % SSID_NAME)
    print("My IP address is", wifi.radio.ipv4_address)

    pool = socketpool.SocketPool(wifi.radio)
    requests = adafruit_requests.Session(pool, ssl.create_default_context())

    print("Fetching json from", WEATHER_URL)

    response = requests.get(WEATHER_URL)

    if response.status_code < 200 or response.status_code >= 300:
        if response.status_code == 500:
            set_text("Got 500 status! Kuuki might be down!", 0)

        magtag.exit_and_deep_sleep(60)

    json_dict = response.json()

    set_text(json_dict["TimeData"] + "\n" + \
             "Temperature: " + str(json_dict["Temp"]) + " C\n" + \
             "Humidity: " + str(json_dict["Humid"]) + " %\n" + \
             "Air Pressure: " + str(json_dict["AirPressure"]) + "\n" + \
             "PM25Standard/Env: " + str(json_dict["PM25Standard"]) + " / " + str(json_dict["PM25Env"]) + "\n" + \
             "PM100Standard/Env: " + str(json_dict["PM100Standard"]) + " / " + str(json_dict["PM100Env"]), 0)

    magtag.exit_and_deep_sleep(60)
def do_test_close_flush(
    extra=b"",
):
    """Test that a chunked response can be closed even when the
    request contents were not accessed."""
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)),)
    chunk = _chunk(TEXT, 33, extra)
    print(chunk)
    sock = mocket.Mocket(HEADERS + chunk)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    response = requests_session.get("http://" + HOST + PATH)

    sock.connect.assert_called_once_with((IP, 80))

    sock.send.assert_has_calls(
        [
            mock.call(b"GET"),
            mock.call(b" /"),
            mock.call(b"testwifi/index.html"),
            mock.call(b" HTTP/1.1\r\n"),
        ]
    )
    sock.send.assert_has_calls(
        [
            mock.call(b"Host: "),
            mock.call(b"wifitest.adafruit.com"),
        ]
    )

    response.close()
def do_test_get_text(
    extra=b"",
):
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)),)
    chunk = _chunk(TEXT, 33, extra)
    print(chunk)
    sock = mocket.Mocket(HEADERS + chunk)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    response = requests_session.get("http://" + HOST + PATH)

    sock.connect.assert_called_once_with((IP, 80))

    sock.send.assert_has_calls(
        [
            mock.call(b"GET"),
            mock.call(b" /"),
            mock.call(b"testwifi/index.html"),
            mock.call(b" HTTP/1.1\r\n"),
        ]
    )
    sock.send.assert_has_calls(
        [
            mock.call(b"Host: "),
            mock.call(b"wifitest.adafruit.com"),
        ]
    )
    assert response.text == str(TEXT, "utf-8")
Exemple #8
0
    def synctime(self, pool):
        try:
            requests = adafruit_requests.Session(pool)
            TIME_API = "http://worldtimeapi.org/api/ip"
            the_rtc = rtc.RTC()
            response = None
            while True:
                try:
                    print("Fetching time")
                    # print("Fetching json from", TIME_API)
                    response = requests.get(TIME_API)
                    break
                except (ValueError, RuntimeError) as e:
                    print("Failed to get data, retrying\n", e)
                    continue

            json1 = response.json()
            # print(json1)
            current_time = json1['datetime']
            the_date, the_time = current_time.split('T')
            year, month, mday = [int(x) for x in the_date.split('-')]
            the_time = the_time.split('.')[0]
            hours, minutes, seconds = [int(x) for x in the_time.split(':')]

            # We can also fill in these extra nice things
            year_day = json1['day_of_year']
            week_day = json1['day_of_week']
            is_dst = json1['dst']

            now = time.struct_time((year, month, mday, hours, minutes, seconds,
                                    week_day, year_day, is_dst))
            the_rtc.datetime = now
        except Exception as e:
            print('[WARNING]', e)
Exemple #9
0
def test_second_send_lies_recv_fails():  # pylint: disable=invalid-name
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(RESPONSE)
    sock2 = mocket.Mocket(RESPONSE)
    pool.socket.side_effect = [sock, sock2]

    ssl = mocket.SSLContext()

    requests_session = adafruit_requests.Session(pool, ssl)
    response = requests_session.get("https://" + HOST + PATH)

    sock.send.assert_has_calls([
        mock.call(b"testwifi/index.html"),
    ])

    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
        mock.call(b"\r\n"),
    ])
    assert response.text == str(TEXT, "utf-8")

    requests_session.get("https://" + HOST + PATH + "2")

    sock.connect.assert_called_once_with((HOST, 443))
    sock2.connect.assert_called_once_with((HOST, 443))
    # Make sure that the socket is closed after send fails.
    sock.close.assert_called_once()
    assert sock2.close.call_count == 0
    assert pool.socket.call_count == 2
Exemple #10
0
def test_get_https_text():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(RESPONSE)
    pool.socket.return_value = sock
    ssl = mocket.SSLContext()

    requests_session = adafruit_requests.Session(pool, ssl)
    response = requests_session.get("https://" + HOST + PATH)

    sock.connect.assert_called_once_with((HOST, 443))

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])
    assert response.text == str(TEXT, "utf-8")

    # Close isn't needed but can be called to release the socket early.
    response.close()
Exemple #11
0
def test_get_https_no_ssl():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(response)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    with pytest.raises(RuntimeError):
        r = s.get("https://" + host + path)
Exemple #12
0
def test_get_https_no_ssl():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(RESPONSE)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    with pytest.raises(RuntimeError):
        requests_session.get("https://" + HOST + PATH)
Exemple #13
0
 def get_request_object(self):
     # Only setup the request object once
     if self.needRequest:
         print("allocating request from pool")
         self.requests = adafruit_requests.Session(
             self.requestPool, ssl.create_default_context()
         )
         self.needRequest = False
     return self.requests
def post_data(msg):
    try:
        socket = socketpool.SocketPool(wifi.radio)
        https = requests.Session(socket, ssl.create_default_context())
        response = https.post(JSON_POST_URL, data=data)
        json_resp = response.json()
    except Exception as e:
        print("Exception in post_data ", str(e))
        uart.write(bytearray("\n\rException in post_data " + str(e)))
        alarm_deepSleep(2)
Exemple #15
0
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)),)
    sock = mocket.Mocket(HEADERS + ENCODED)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    response = requests_session.get("http://" + HOST + "/get")
    sock.connect.assert_called_once_with((IP, 80))
    assert response.json() == RESPONSE
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(headers + encoded)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    r = s.get("http://" + host + "/get")
    sock.connect.assert_called_once_with((ip, 80))
    assert r.json() == response
def test_string():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(headers + encoded)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    data = "31F"
    r = s.post("http://" + host + "/post", data=data)
    sock.connect.assert_called_once_with((ip, 80))
    sock.send.assert_called_with(b"31F")
def test_string():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(HEADERS + ENCODED)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    data = "31F"
    requests_session.post("http://" + HOST + "/post", data=data)
    sock.connect.assert_called_once_with((IP, 80))
    sock.send.assert_called_with(b"31F")
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(HEADERS + ENCODED)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    json_data = {"Date": "July 25, 2019"}
    requests_session.post("http://" + HOST + "/post", json=json_data)
    sock.connect.assert_called_once_with((IP, 80))
    sock.send.assert_called_with(b'{"Date": "July 25, 2019"}')
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(headers + encoded)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    json_data = {"Date": "July 25, 2019"}
    r = s.post("http://" + host + "/post", json=json_data)
    sock.connect.assert_called_once_with((ip, 80))
    sock.send.assert_called_with(b'{"Date": "July 25, 2019"}')
Exemple #21
0
    def connect(self, ssid, password):
        """
        Connect to the WiFi Network using the information provided

        :param ssid: The WiFi name
        :param password: The WiFi password

        """
        wifi.radio.connect(ssid, password)
        pool = socketpool.SocketPool(wifi.radio)
        self.requests = adafruit_requests.Session(pool,
                                                  ssl.create_default_context())
        self._connected = True
def initialise_wifi():
    """
    Connect to WiFi as configured in `secrets.py`
    """
    print("Initialising WiFi ...")
    try:
        from secrets import secrets
    except ImportError:
        print("WiFi secrets are kept in secrets.py, please add them there!")
        raise

    wifi.radio.connect(secrets["ssid"], secrets["password"])
    pool = socketpool.SocketPool(wifi.radio)
    requests = adafruit_requests.Session(pool, ssl.create_default_context())
    print("Initialising WiFi ... {} connected".format(secrets['ssid']))
    return(requests)
Exemple #23
0
 def __init__(self, app_id, password, tenant_id, subscription_id):
     """
     Parameters:
     -----------
     app_id : str
         The application id from Azure
     password : str
         Secret generated by Azure for the application
     Tenant_id : str
         tenant id for the application
     subscription_id : str
         Azure subscription id
     """
     self._app_id = app_id
     self._password = password
     self._tenant_id = tenant_id
     self._subscription_id = subscription_id
     pool = socketpool.SocketPool(wifi.radio)
     self._https = requests.Session(pool, ssl.create_default_context())
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(RESPONSE_HEADERS)
    pool.socket.return_value = sock
    sent = []

    def _send(data):
        sent.append(data)  # pylint: disable=no-member
        return len(data)

    sock.send.side_effect = _send

    requests_session = adafruit_requests.Session(pool)
    headers = {"user-agent": "blinka/1.0.0"}
    requests_session.get("http://" + HOST + "/get", headers=headers)

    sock.connect.assert_called_once_with((IP, 80))
    sent = b"".join(sent).lower()
    assert b"user-agent: blinka/1.0.0\r\n" in sent
Exemple #25
0
def test_json():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)),)
    sock = mocket.Mocket(response_headers)
    pool.socket.return_value = sock
    sent = []

    def _send(data):
        sent.append(data)
        return len(data)

    sock.send.side_effect = _send

    s = adafruit_requests.Session(pool)
    headers = {"user-agent": "blinka/1.0.0"}
    r = s.get("http://" + host + "/get", headers=headers)

    sock.connect.assert_called_once_with((ip, 80))
    sent = b"".join(sent).lower()
    assert b"user-agent: blinka/1.0.0\r\n" in sent
def test_method():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(headers + encoded)
    pool.socket.return_value = sock

    s = adafruit_requests.Session(pool)
    r = s.post("http://" + host + "/post")
    sock.connect.assert_called_once_with((ip, 80))

    sock.send.assert_has_calls([
        mock.call(b"POST"),
        mock.call(b" /"),
        mock.call(b"post"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"httpbin.org"),
    ])
def test_method():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(HEADERS + ENCODED)
    pool.socket.return_value = sock

    requests_session = adafruit_requests.Session(pool)
    requests_session.post("http://" + HOST + "/post")
    sock.connect.assert_called_once_with((IP, 80))

    sock.send.assert_has_calls([
        mock.call(b"POST"),
        mock.call(b" /"),
        mock.call(b"post"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"httpbin.org"),
    ])
Exemple #28
0
def test_connect_out_of_memory():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), )
    sock = mocket.Mocket(RESPONSE)
    sock2 = mocket.Mocket(RESPONSE)
    sock3 = mocket.Mocket(RESPONSE)
    pool.socket.side_effect = [sock, sock2, sock3]
    sock2.connect.side_effect = MemoryError()
    ssl = mocket.SSLContext()

    requests_session = adafruit_requests.Session(pool, ssl)
    response = requests_session.get("https://" + HOST + PATH)

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])
    assert response.text == str(TEXT, "utf-8")

    response = requests_session.get("https://" + HOST2 + PATH)
    sock3.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock3.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest2.adafruit.com"),
    ])

    assert response.text == str(TEXT, "utf-8")
    sock.close.assert_called_once()
    sock.connect.assert_called_once_with((HOST, 443))
    sock3.connect.assert_called_once_with((HOST2, 443))
def test_connect_out_of_memory():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(response)
    sock2 = mocket.Mocket(response)
    sock3 = mocket.Mocket(response)
    pool.socket.side_effect = [sock, sock2, sock3]
    sock2.connect.side_effect = MemoryError()
    ssl = mocket.SSLContext()

    s = adafruit_requests.Session(pool, ssl)
    r = s.get("https://" + host + path)

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])
    assert r.text == str(text, "utf-8")

    r = s.get("https://" + host2 + path)
    sock3.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock3.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest2.adafruit.com"),
    ])

    assert r.text == str(text, "utf-8")
    sock.close.assert_called_once()
    sock.connect.assert_called_once_with((host, 443))
    sock3.connect.assert_called_once_with((host2, 443))
def test_get_twice_after_second():
    pool = mocket.MocketPool()
    pool.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), )
    sock = mocket.Mocket(response + response)
    pool.socket.return_value = sock
    ssl = mocket.SSLContext()

    s = adafruit_requests.Session(pool, ssl)
    r = s.get("https://" + host + path)

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])

    r2 = s.get("https://" + host + path + "2")

    sock.send.assert_has_calls([
        mock.call(b"GET"),
        mock.call(b" /"),
        mock.call(b"testwifi/index.html2"),
        mock.call(b" HTTP/1.1\r\n"),
    ])
    sock.send.assert_has_calls([
        mock.call(b"Host: "),
        mock.call(b"wifitest.adafruit.com"),
    ])
    sock.connect.assert_called_once_with((host, 443))
    pool.socket.assert_called_once()

    with pytest.raises(RuntimeError):
        r.text == str(text, "utf-8")