예제 #1
0
 def test_maxRequests_maximumIsZero(self, mock_urlopen):
     mockRead = MagicMock()
     mockRead.read.return_value = "ServerResponse"
     mock_urlopen.return_value = mockRead
     comm = Communicator(maxRequestsPerDay=0)
     with pytest.raises(ApiLimitException):
         comm.sendRequest_withCounter("someUrl")
     assert mock_urlopen.call_count == 0
예제 #2
0
    def test_maxRequests_requestsAvailable(self, mock_urlopen):
        mockRead = MagicMock()
        mockRead.read.return_value = "ServerResponse"
        mock_urlopen.return_value = mockRead

        comm = Communicator(maxRequestsPerDay=20)
        assert comm.sendRequest_withCounter("someUrl") == "ServerResponse"
        assert mock_urlopen.call_count == 1 #assert_called_once()
예제 #3
0
    def test_maxRequests_tooManyRequestsYesterday_shouldWorkToday(self, mock_urlopen):
        mockRead = MagicMock()
        mockRead.read.return_value = "ServerResponse"
        mock_urlopen.return_value = mockRead

        comm = Communicator(maxRequestsPerDay=2)
        comm.currentCount = 5
        comm.counterDate = datetime.today() - timedelta(1)
        assert comm.sendRequest_withCounter("someUrl") == "ServerResponse"
        assert mock_urlopen.call_count == 1
        assert comm.counterDate == datetime.today().date()
        assert comm.currentCount == 1
예제 #4
0
파일: tpg.py 프로젝트: stklik/tpg.now
    def getNextDeparturesForStop(args):
        ''' Returns Lines (code, destination) to departureTimes (in seconds) '''
        json = None
        if args.lines:
            json = Communicator.Instance().sendRequest_getJSON("GetNextDepartures", stopCode=args.stop.code, linesCode=",".join([l.code for l in args.lines]))
        else:
            json = Communicator.Instance().sendRequest_getJSON("GetNextDepartures", stopCode=args.stop.code)

        stop = Stop.fromJson(json["stop"])

        departures = [Departure.fromJson(dep) for dep in json["departures"]]
        departuresFiltered = [dep for dep in departures if dep]
        return stop, departuresFiltered
예제 #5
0
    def test_getLineColour_nonExistingColour_returnsNone(self):
        mockColours = """
{"timestamp":"2017-02-20T15:42:49+0100",
"colors":[
{"lineCode":"18","hexa":"cc3399","background":"cc3399","text":"FFFFFF"},
{"lineCode":"F","hexa":"FF9999","background":"FF9999","text":"000000"},
{"lineCode":"Y","hexa":"FF9999","background":"FF9999","text":"000000"},
{"lineCode":"Z","hexa":"FF9999","background":"FF9999","text":"000000"}]}
"""
        mock = Communicator()
        mock.sendRequest = MagicMock(return_value=mockColours)
        Communicator.instance = mock

        assert Tpg.getLineColor("B") == None
예제 #6
0
파일: tpg.py 프로젝트: stklik/tpg.now
    def getLineColors():
        ''' Returns a dictionary of {line: colour} '''
        json = Communicator.Instance().sendRequest_getJSON("GetLinesColors")

        linesToColors = dict()
        for color in json["colors"]:
            linesToColors[color["lineCode"]] = {
                "background": color["background"],
                "foreground": color["text"]
                }
        return linesToColors
예제 #7
0
파일: tpg.py 프로젝트: stklik/tpg.now
    def getTodaysStopsAndLines():
        todaysStops = "todaysStops"
        todaysLines = "todaysLines"

        if Tpg.cache.has(todaysLines):
            return Tpg.cache.read(todaysStops), Tpg.cache.read(todaysLines)

        json = Communicator.Instance().sendRequest_getJSON("GetStops")
        stops = [Stop(s["stopCode"],s["stopName"]) for s in json["stops"]]

        lines = []
        for stop in json["stops"]:
            for connection in stop["connections"]:
                line = Line(connection["lineCode"], connection["destinationName"])
                if line not in lines:
                    lines.append(line)
        Tpg.cache.write(todaysStops, stops, delay=Tpg.cacheTime)  # cache for an hour
        Tpg.cache.write(todaysLines, lines, delay=Tpg.cacheTime)

        return stops,lines
예제 #8
0
 def test_sendRequest_getJSON_athrowsParseException(self):
     mock = Communicator()
     mock.sendRequest = MagicMock(return_value="""{"abc": 12}""")
     assert mock.sendRequest_getJSON("command") == json.loads("""{"abc": 12}""")
예제 #9
0
 def test_sendRequest_getJSON_throwsParseException(self):
     mock = Communicator()
     mock.sendRequest = MagicMock(return_value="""{ dcac:}""")
     with pytest.raises(JSONError):
         mock.sendRequest_getJSON("command")
예제 #10
0
 def comm(self):
     comm = Communicator(apiKey="testKey", baseURL="http://data.tpg.ch",
         apiVersion="v99",responseFormat="json")
     return comm
예제 #11
0
파일: app.py 프로젝트: stklik/tpg.now
import os
import logging
from flask import Flask, request, redirect

from config import Config
from tpgnow.server import Server
from tpgnow.communicator import Communicator

logging.basicConfig(level=logging.DEBUG)


app = Flask(__name__)
app.debug = True

# setup Communicator
Communicator.Instance().apiKey = os.getenv("API_KEY", Config.apiKey)

server = Server()

def _get_agent_and_baseurl(request):
    agent = request.headers.get('User-Agent')
    baseurl = request.headers.get('Host')
    url = request.url
    print(url)
    return {"agent" : agent, "baseurl": baseurl, "url": url}

@app.route('/help')
def help():
    requestArgs = _get_agent_and_baseurl(request)
    response = server.getHelp(**requestArgs)
    return server.reply(response, **requestArgs)