Ejemplo n.º 1
0
def fValidTestOk(test):
    global g_errors, g_testNumbers

    testNo = test[0]
    if g_testNumbers.has_key(testNo):
        print "Duplicate test number: %d" % testNo
        sys.exit(0)
    else:
        g_testNumbers[
            testNo] = 1  # can be anything, we only use it to test if the entry exists

    fieldsToSend = test[1]
    assert isinstance(fieldsToSend, list)
    expectedResultFields = test[2]
    assert 0 == len(fieldsToSend) % 2
    req = getRequestHandleCookie()
    fieldsCount = len(fieldsToSend) / 2
    for fieldNo in range(fieldsCount):
        fieldName = fieldsToSend[fieldNo * 2]
        fieldValue = fieldsToSend[fieldNo * 2 + 1]
        req.addField(fieldName, fieldValue)
    rsp = Response(req)
    client.handleCookie(rsp)
    errorsTxt = []

    if not rsp.hasField(Fields.transactionId):
        errorsTxt.append("Field %s missing" % Fields.transactionId)
    else:
        tridGot = rsp.getFieldShort(Fields.transactionId)
        tridSent = req.transactionId
        if tridGot != tridSent:
            errorsTxt.append("Sent transactionId %s but got %s" %
                             (tridSent, tridGot))
    for fieldName in expectedResultFields:
        if isinstance(fieldName, list):
            assert 2 == len(fieldName)
            fieldValue = fieldName[1]
            fieldName = fieldName[0]
            if not rsp.hasField(fieldName):
                errorsTxt.append("Field %s missing" % fieldName)
            else:
                if fieldValue != rsp.getFieldShort(fieldName):
                    errorsTxt.append(
                        "Field %s value is different, expected: %s, got: %s" %
                        (fieldName, fieldValue, rsp.getFieldShort(fieldName)))
        else:
            if not rsp.hasField(fieldName):
                errorsTxt.append("Field %s missing" % fieldName)
    if len(errorsTxt) > 0:
        errorsTxt.append("Full request:\n'%s'" % req.getText())
        errorsTxt.append("Full response:\n'%s'" % rsp.getShortText())
        g_errors[testNo] = errorsTxt
        return False
    else:
        return True
Ejemplo n.º 2
0
 def getResponse(self, requiredFields=[]):
     self.rsp = Response(self.req)
     self.assertFieldsExist(self.rsp, requiredFields)
     if self.rsp.hasField(Fields.transactionId):
         self.assertEqual(self.rsp.getField(Fields.transactionId),
                          self.req.transactionId)
Ejemplo n.º 3
0
class ServerTests(unittest.TestCase):
    def assertFieldExists(self, response, field):
        # list of fields in fields is threated as alternative (one or more from list)
        if isinstance(field, list):
            wasField = 0
            for smallField in field:
                if response.hasField(smallField):
                    wasField = 1
                    self.assertEqual(response.hasField(smallField), True)
            if 0 == wasField:
                print "\nnone of: '%s' does exist in response" % string.join(
                    field, "', '")
                print "all fields: %s" % string.join(response.getFields(), ",")
                if response.hasField(Fields.error):
                    print "Error: %s" % response.getField(Fields.error)
        else:
            if not response.hasField(field):
                print "\nfield '%s' doesn't exist in response" % field
                print "all fields: %s" % string.join(response.getFields(), ",")
                if response.hasField(Fields.error):
                    print "Error: %s" % response.getField(Fields.error)
            self.assertEqual(response.hasField(field), True)

    def assertFieldDoesntExist(self, response, field):
        if response.hasField(field):
            print "\nfield '%s' exist in response" % field
            print "all fields: %s" % string.join(response.getFields(), ",")
        self.assertEqual(response.hasField(field), False)

    def assertFieldsDontExist(self, response, fields):
        for field in fields:
            self.assertFieldDoesntExist(response, field)

    def assertFieldsExist(self, response, fields):
        for field in fields:
            self.assertFieldExists(response, field)

    def assertFieldEqual(self, response, field, value):
        # all values returned by server are strings. If value to compare with
        # is int, change it to string. This makes it easier to e.g. compare
        # server errors
        if isinstance(value, int):
            value = "%d" % value
        self.assertEqual(response.getField(field), value)

    def addField(self, fieldName, fieldValue):
        self.req.addField(fieldName, fieldValue)

    def getResponse(self, requiredFields=[]):
        self.rsp = Response(self.req)
        self.assertFieldsExist(self.rsp, requiredFields)
        if self.rsp.hasField(Fields.transactionId):
            self.assertEqual(self.rsp.getField(Fields.transactionId),
                             self.req.transactionId)

    def assertError(self, expectedError):
        self.assertFieldEqual(self.rsp, Fields.error, expectedError)

    def test_Ping(self):
        # this is the simplest valid requests - only sends transaction id
        # in response server sends the same transaction id
        self.req = getRequestHandleCookie()
        self.getResponse([Fields.cookie, Fields.transactionId])

    def test_MalformedRequest(self):
        self.req = getRequestHandleCookie()
        # malformed, because there is no ":"
        self.req.addLine("malformed\n")
        self.getResponse([Fields.error, Fields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def verifyArgument(self, field, fRequiresArguments):
        self.req = getRequestHandleCookie()
        # do the exact opposite of what's expected
        if fRequiresArguments:
            self.req.addField(field, None)
        else:
            self.req.addField(field, "not needed argument")
        self.getResponse([Fields.error, Fields.transactionId])
        if fRequiresArguments:
            self.assertError(ServerErrors.requestArgumentMissing)
        else:
            self.assertError(ServerErrors.unexpectedRequestArgument)

    # check if server correctly detects missing extra arguments
    def test_ArgumentsWithoutValue(self):
        fieldsWithoutValue = [
            Fields.getRegCodeDaysToExpire, Fields.getCurrentBoxOffice
        ]
        for field in fieldsWithoutValue:
            self.verifyArgument(field, False)

    # check if server correctly detects missing arguments
    def test_ArgumentsWithValue(self):
        fieldsWithValue = [
            Fields.protocolVersion, Fields.clientInfo, Fields.transactionId,
            Fields.cookie, Fields.getCookie, Fields.getMovies, Fields.regCode,
            Fields.verifyRegCode
        ]
        for field in fieldsWithValue:
            self.verifyArgument(field, True)

    def prepareRecipeList(self, query):
        self.req = getRequestHandleCookie(Fields.getRecipesList, query)

    def doRecipeGetListOk(self, query):
        self.prepareRecipeList(query)
        self.getResponse([Fields.recipiesList, Fields.transactionId])

    def test_RecipeBread(self):
        self.doRecipeGetListOk("bread")

    def test_RecipeApricot(self):
        self.doRecipeGetListOk("apricot")

    def doRecipeEmptyList(self, query):
        self.prepareRecipeList(query)
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_RecipeEmptyList(self):
        self.doRecipeEmptyList("asdfaawer")

    def prepareRecipe(self, query):
        self.req = getRequestHandleCookie(Fields.getRecipe, query)

    def test_RecipeValid(self):
        self.prepareRecipe("/recipes/recipe_views/views/104527")
        self.getResponse([Fields.recipe, Fields.transactionId])

    def test_RecipeInvalid(self):
        self.prepareRecipe("/recipes/recipe_views/views/asdgasdf")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_RecipeInvalid2(self):
        self.prepareRecipe("/asdfadgasdf")
        self.getResponse([Fields.transactionId])
        self.assertError(ServerErrors.moduleTemporarilyDown)

    def test_OnlyOneRequest(self):
        self.prepareRecipe("bread")
        self.addField(Fields.getMovies, "98101")
        self.getResponse([Fields.transactionId])
        self.assertError(ServerErrors.serverFailure)

    def prepareWeather(self, location):
        self.req = getRequestHandleCookie(Fields.getWeather, location)

    def test_WeatherLocationUnknown(self):
        self.prepareWeather("66666")
        self.getResponse([Fields.locationUnknown, Fields.transactionId])

    def test_WeatherLocationAmbig(self):
        self.prepareWeather("warsaw")
        self.getResponse([Fields.weatherMultiselect, Fields.transactionId])

    def test_WeatherValidLocation(self):
        self.prepareWeather("PLXX0005")
        self.getResponse([Fields.weather, Fields.transactionId])

    def test_WeatherValidZipLocation(self):
        self.prepareWeather("98101")
        self.getResponse([Fields.weather, Fields.transactionId])

    def prepareDream(self, dream):
        self.req = getRequestHandleCookie(Fields.getDream, dream)

    def test_DreamNoResults(self):
        self.prepareDream("abrakadabrabumcykcyk")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_DreamOkTooth(self):
        self.prepareDream("tooth")
        self.getResponse([Fields.outDream, Fields.transactionId])

    def test_DreamOkSex(self):
        self.prepareDream("sex")
        self.getResponse([Fields.outDream, Fields.transactionId])

    def prepareJokesList(self, query):
        self.req = getRequestHandleCookie(Fields.getJokesList, query)

    def test_JokesListNoResults(self):
        self.prepareJokesList("0;rating;;;;blahhphdsA")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_JokesListOk1(self):
        self.prepareJokesList("0;rating;;;;test")
        self.getResponse([Fields.outJokesList, Fields.transactionId])

    def test_JokesListOk2(self):
        self.prepareJokesList("0;rating;Racy;QandA;Blonde;test")
        self.getResponse([Fields.outJokesList, Fields.transactionId])

    def test_JokesListOk3(self):
        self.prepareJokesList("4;rating;;;;")
        self.getResponse([Fields.outJokesList, Fields.transactionId])

    def prepareJoke(self, url):
        self.req = getRequestHandleCookie(Fields.getJoke, url)

    def test_JokeOk(self):
        self.prepareJoke("/results/detail.asp?sql=8&id=6358")
        self.getResponse([Fields.outJoke, Fields.transactionId])

    def test_JokeOkRandom(self):
        self.prepareJoke("random")
        self.getResponse([Fields.outJoke, Fields.transactionId])

    def test_JokeOkRandom2(self):  ## to test cache
        self.prepareJoke("random")
        self.getResponse([Fields.outJoke, Fields.transactionId])

    def test_JokeOkRandom3(self):  ## to test cache
        self.prepareJoke("random")
        self.getResponse([Fields.outJoke, Fields.transactionId])

    def prepare411PersonSearch(self, query):
        self.req = getRequestHandleCookie(Fields.get411PersonSearch, query)

    def test_411PersonSearchOk(self):
        self.prepare411PersonSearch(",Kowalczyk,98101,WA")
        self.getResponse(
            [Fields.out411PersonSearchResult, Fields.transactionId])

    def test_411PersonSearchNoCity(self):
        self.prepare411PersonSearch(",Kowalczyk,blahblah,WA")
        self.getResponse([[Fields.outNoResults, Fields.out411NoCity],
                          Fields.transactionId])

    def test_411PersonSearchTooManyResults(self):
        self.prepare411PersonSearch(",K,,WA")
        self.getResponse([Fields.out411TooManyResults, Fields.transactionId])

    def test_411PersonSearchNoResults(self):
        self.prepare411PersonSearch("Hulianno,Kowalczykos,Seattle,WA")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_411PersonSearchCityMultiselect(self):
        self.prepare411PersonSearch(",Kowal,Sea,WA")
        self.getResponse(
            [[Fields.out411PersonSearchCityMultiselect, Fields.outNoResults],
             Fields.transactionId])

    def prepare411BusinessSearch(self, query):
        self.req = getRequestHandleCookie(Fields.get411BusinessSearch, query)

    def test_411BusinessSearchOk(self):
        self.prepare411BusinessSearch("hair,seattle,WA,No,Name")
        self.getResponse(
            [Fields.out411BusinessSearchResult, Fields.transactionId])

    def test_411BusinessSearchOk2(self):
        self.prepare411BusinessSearch("hair,seattle,WA,Yes,Name")
        self.getResponse(
            [Fields.out411BusinessSearchResult, Fields.transactionId])

    def test_411BusinessSearchOk3(self):
        self.prepare411BusinessSearch("hair,seattle,WA,No,Category")
        self.getResponse(
            [Fields.out411BusinessSearchMultiselect, Fields.transactionId])

    def test_411BusinessSearchOk4(self):
        self.prepare411BusinessSearch("hair,seattle,WA,Yes,Category")
        self.getResponse(
            [Fields.out411BusinessSearchMultiselect, Fields.transactionId])

    def test_411BusinessSearchNoCity(self):
        self.prepare411BusinessSearch("hair,blahblah,WA,No,Category")
        self.getResponse([Fields.out411NoCity, Fields.transactionId])

    def test_411BusinessSearchNoCity2(self):
        self.prepare411BusinessSearch("hair,blahblah,WA,No,Name")
        self.getResponse([Fields.out411NoCity, Fields.transactionId])

    def test_411BusinessSearchNoResults(self):
        self.prepare411BusinessSearch("hairscalpindians,,WA,No,Name")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_411BusinessSearchNoResults2(self):
        self.prepare411BusinessSearch("hairscalpindians,,WA,No,Category")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepare411International(self, query):
        self.req = getRequestHandleCookie(Fields.get411InternationalCodeSearch,
                                          query)

    def test_411International(self):
        self.prepare411International("PL")
        self.getResponse(
            [Fields.out411InternationalCodeSearchResult, Fields.transactionId])

    def test_411International2(self):
        self.prepare411International("DZ")
        self.getResponse(
            [Fields.out411InternationalCodeSearchResult, Fields.transactionId])

    def test_411International3(self):
        self.prepare411International("GO")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepare411ReversePhone(self, query):
        self.req = getRequestHandleCookie(Fields.get411ReversePhone, query)

    def test_411ReversePhoneOk(self):
        self.prepare411ReversePhone("425-882-0110")
        self.getResponse(
            [Fields.out411ReversePhoneResult, Fields.transactionId])

    def test_411ReversePhoneOk2(self):
        self.prepare411ReversePhone("216-479-2500")
        self.getResponse(
            [Fields.out411ReversePhoneResult, Fields.transactionId])

    def test_411ReversePhoneNoResults(self):
        self.prepare411ReversePhone("555-555-5555")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def test_411ReversePhoneMalformed(self):
        self.prepare411ReversePhone("20820110")
        self.getResponse([Fields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def prepare411AreaByCity(self, query):
        self.req = getRequestHandleCookie(Fields.get411AreaByCity, query)

    def test_411AreaByCityOk(self):
        self.prepare411AreaByCity("seattle,WA")
        self.getResponse([Fields.out411AreaByCityResult, Fields.transactionId])

    def test_411AreaByCityMultiselect(self):
        self.prepare411AreaByCity("sea,WA")
        self.getResponse(
            [Fields.out411AreaByCityMultiselect, Fields.transactionId])

    def test_411AreaByCityNoResults(self):
        self.prepare411AreaByCity("blahblah,WA")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepare411ReverseArea(self, query):
        self.req = getRequestHandleCookie(Fields.get411ReverseArea, query)

    def test_411ReverseAreaOk(self):
        self.prepare411ReverseArea("206")
        self.getResponse(
            [Fields.out411ReverseAreaResult, Fields.transactionId])

    def test_411ReverseArea911(self):
        self.prepare411ReverseArea("911")
        self.getResponse(
            [Fields.out411ReverseAreaResult, Fields.transactionId])

    def test_411ReverseAreaNoResults(self):
        self.prepare411ReverseArea("555")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepare411ZipByCity(self, query):
        self.req = getRequestHandleCookie(Fields.get411ZipByCity, query)

    def test_411ZipByCityOk(self):
        self.prepare411ZipByCity("seattle,WA")
        self.getResponse([Fields.out411ZipByCityResult, Fields.transactionId])

    def test_411ZipByCityMultiselect(self):
        self.prepare411ZipByCity("sea,WA")
        self.getResponse(
            [Fields.out411ZipByCityMultiselect, Fields.transactionId])

    def test_411ZipByCityNoResults(self):
        self.prepare411ZipByCity("blahblah,WA")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepare411ReverseZip(self, query):
        self.req = getRequestHandleCookie(Fields.get411ReverseZip, query)

    def test_411ReverseZipOk(self):
        self.prepare411ReverseZip("98101")
        self.getResponse([Fields.out411ReverseZipResult, Fields.transactionId])

    def test_411ReverseZipNoResults(self):
        self.prepare411ReverseZip("66666")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepareCurrencies(self):
        self.req = getRequestHandleCookie(Fields.getCurrencyConversion)

    def test_CurrenciesOK(self):
        self.prepareCurrencies()
        self.getResponse([Fields.outCurrencyConversion, Fields.transactionId])

    def prepareStocksList(self, query):
        self.req = getRequestHandleCookie(Fields.getStocksList, query)

    def test_StocksListOK(self):
        self.prepareStocksList("^DJI;^IXIC;^GSPC")
        self.getResponse([Fields.outStocksList, Fields.transactionId])

    def test_StocksListOK2(self):
        self.prepareStocksList("MSFT")
        self.getResponse([Fields.outStocksList, Fields.transactionId])

    def test_StocksListOK3(self):
        self.prepareStocksList("microsoft;prokom")
        self.getResponse([Fields.outStocksList, Fields.transactionId])

    def prepareStocksListValidateLast(self, query):
        self.req = getRequestHandleCookie(Fields.getStocksListValidateLast,
                                          query)

    def test_StocksListValidateLastValid(self):
        self.prepareStocksListValidateLast("YHOO;MSFT")
        self.getResponse([Fields.outStocksList, Fields.transactionId])

    def test_StocksListValidateLastByName(self):
        self.prepareStocksListValidateLast("YHOO;microsoft")
        self.getResponse([Fields.outStocksListByName, Fields.transactionId])

    def test_StocksListValidateLastNoResults(self):
        self.prepareStocksListValidateLast("YHOO;notValidSymbolOrName")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepareStockByName(self, url):
        self.req = getRequestHandleCookie(Fields.getStockByName, url)

    def test_StockByNameOk(self):
        self.prepareStockByName("/l?s=WHAT")
        self.getResponse([Fields.outStocksListByName, Fields.transactionId])

    def test_StockByNameNoResults(self):
        self.prepareStockByName("/l?s=nothingFindForThis")
        self.getResponse([Fields.outNoResults, Fields.transactionId])

    def prepareStock(self, url):
        self.req = getRequestHandleCookie(Fields.getStock, url)

    def test_StockOk(self):
        self.prepareStock("/q?s=^GSPC")
        self.getResponse([Fields.outStock, Fields.transactionId])

    def test_StockOk2(self):
        self.prepareStock("/q?s=MSFT")
        self.getResponse([Fields.outStock, Fields.transactionId])

    def prepareAmazonBrowse(self, url):
        self.req = getRequestHandleCookie(Fields.getAmazonBrowse, url)

    # TODO: rewrite those tests to use Get-Url
    #def test_AmazonBrowseOk(self):
    #    self.prepareAmazonBrowse("Blended;Books;1")
    #    self.getResponse([Fields.outAmazonBrowse, Fields.transactionId])

    #def test_AmazonBrowseOk1(self):
    #    self.prepareAmazonBrowse("Blended;DVD;1")
    #    self.getResponse([Fields.outAmazonBrowse, Fields.transactionId])

    #def test_AmazonBrowseOk2(self):
    #    self.prepareAmazonBrowse("Books;26;1")
    #    self.getResponse([Fields.outAmazonBrowse, Fields.transactionId])

    #def prepareAmazonSearch(self, url):
    #    self.req = getRequestHandleCookie(Fields.getAmazonSearch, url)

    #def test_AmazonSearchOk(self):
    #    self.prepareAmazonSearch("Books;;1;bb")
    #    self.getResponse([Fields.outAmazonSearch, Fields.transactionId])

    #def test_AmazonSearchNoResults(self):
    #    self.prepareAmazonSearch("Books;;1;ahfafhssafa")
    #    self.getResponse([Fields.outNoResults, Fields.transactionId])

    #def prepareAmazonItem(self, url):
    #    self.req = getRequestHandleCookie(Fields.getAmazonItem, url)

    #def test_AmazonItemOk(self):
    #    self.prepareAmazonItem("073984072X")
    #    self.getResponse([Fields.outAmazonItem, Fields.transactionId])

    #def prepareAmazonList(self, url):
    #    self.req = getRequestHandleCookie(Fields.getAmazonList, url)

    #def test_AmazonListOk(self):
    #    self.prepareAmazonList("L1WOW1VSS7JWSN;1")
    #    self.getResponse([Fields.outAmazonSearch, Fields.transactionId])

    #def prepareAmazonWishlistSearch(self, wstr):
    #    self.req = getRequestHandleCookie(Fields.getAmazonWishlist, wstr)

    #def test_AmazonWishlistSearchOk(self):
    #    self.prepareAmazonWishlistSearch("Kowalczyk;;;;1")
    #    self.getResponse([Fields.outAmazonWishlist, Fields.transactionId])

    def prepareHoroscope(self, query):
        self.req = getRequestHandleCookie(Fields.getHoroscope, query)

    def test_HoroscopesOk(self):
        self.prepareHoroscope("Aries")
        self.getResponse([Fields.outHoroscope, Fields.transactionId])

    def test_HoroscopesOk2(self):
        self.prepareHoroscope("yh;/astrology/careerfinance/monthly/aries")
        self.getResponse([Fields.outHoroscope, Fields.transactionId])

    def test_HoroscopesOk3(self):
        self.prepareHoroscope("yh;/astrology/general/dailyteen/aries")
        self.getResponse([Fields.outHoroscope, Fields.transactionId])

    def test_HoroscopesOk4(self):
        self.prepareHoroscope("yh;/astrology/love/weekly/aries")
        self.getResponse([Fields.outHoroscope, Fields.transactionId])

    def prepareTvListingsProviders(self, zipCode):
        self.req = getRequestHandleCookie(Fields.getTvListingsProviders,
                                          zipCode)

    def test_TvLisitingsProviders(self):
        self.prepareTvListingsProviders('98101')
        self.getResponse([Fields.outTvListingsProviders, Fields.transactionId])

    def test_RegisterAndAskVersion(self):
        # TODO write this test
        pass
Ejemplo n.º 4
0
class ServerTests(unittest.TestCase):
    def assertFieldExists(self, response, field):
        if not response.hasField(field):
            print "\nfield '%s' doesn't exist in response" % field
            print "all fields: %s" % string.join(response.getFields(), ",")
            if response.hasField(iPediaFields.error):
                print "Error: %s" % response.getField(iPediaFields.error)
        self.assertEqual(response.hasField(field), True)

    def assertFieldDoesntExist(self, response, field):
        if response.hasField(field):
            print "\nfield '%s' exist in response" % field
            print "all fields: %s" % string.join(response.getFields(), ",")
        self.assertEqual(response.hasField(field), False)

    def assertFieldsDontExist(self, response, fields):
        for field in fields:
            self.assertFieldDoesntExist(response, field)

    def assertFieldsExist(self, response, fields):
        for field in fields:
            self.assertFieldExists(response, field)

    def assertFieldEqual(self, response, field, value):
        # all values returned by server are strings. If value to compare with
        # is int, change it to string. This makes it easier to e.g. compare
        # server errors
        if isinstance(value, int):
            value = "%d" % value
        self.assertEqual(response.getField(field), value)

    def getResponse(self, requiredFields=[]):
        self.rsp = Response(self.req)
        self.assertFieldsExist(self.rsp, requiredFields)
        if self.rsp.hasField(iPediaFields.transactionId):
            self.assertEqual(self.rsp.getField(iPediaFields.transactionId),
                             self.req.transactionId)

    def assertError(self, expectedError):
        self.assertFieldEqual(self.rsp, iPediaFields.error, expectedError)

    def test_Ping(self):
        # this is the simplest valid requests - only sends transaction id
        # in response server sends the same transaction id
        self.req = getRequestHandleCookie()
        self.getResponse([iPediaFields.cookie, iPediaFields.transactionId])

    def test_MalformedRequest(self):
        self.req = getRequestHandleCookie()
        # malformed, because there is no ":"
        self.req.addLine("malformed\n")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_MissingArgument(self):
        self.req = getRequestHandleCookie()
        # Get-Cookie requires an argument but we're not sending it
        self.req.addField(iPediaFields.getCookie, None)
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.requestArgumentMissing)

    def test_ExtraArgument(self):
        self.req = getRequestHandleCookie()
        # Get-Random-Article doesn't require an argument, but we're sending it
        self.req.addField(iPediaFields.getRandom, "not needed")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.unexpectedRequestArgument)

    def verifyArgument(self, field, fRequiresArguments):
        self.req = getRequestHandleCookie()
        # do the exact opposite of what's expected
        if fRequiresArguments:
            self.req.addField(field, None)
        else:
            self.req.addField(field, "not needed argument")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        if fRequiresArguments:
            self.assertError(ServerErrors.requestArgumentMissing)
        else:
            self.assertError(ServerErrors.unexpectedRequestArgument)

    # check if server correctly detects missing extra arguments
    def test_ArgumentsWithoutValue(self):
        fieldsWithoutValue = [
            iPediaFields.getRandom, iPediaFields.getArticleCount,
            iPediaFields.getDatabaseTime
        ]
        for field in fieldsWithoutValue:
            self.verifyArgument(field, False)

    # check if server correctly detects missing arguments
    def test_ArgumentsWithValue(self):
        fieldsWithValue = [
            iPediaFields.protocolVersion, iPediaFields.clientInfo,
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.getCookie, iPediaFields.getArticle,
            iPediaFields.regCode, iPediaFields.search,
            iPediaFields.verifyRegCode
        ]
        for field in fieldsWithValue:
            self.verifyArgument(field, True)

    def test_UnrecognizedField(self):
        self.req = getRequestHandleCookie("Foo", "blast")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidRequest)

    def test_VerifyValidRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.verifyRegCode,
                                          testValidRegCode)
        self.getResponse([
            iPediaFields.cookie, iPediaFields.transactionId,
            iPediaFields.regCodeValid
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.regCodeValid, 1)

    def test_VerifyInvalidRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.verifyRegCode,
                                          invalidRegCodeNumber)
        self.getResponse([
            iPediaFields.cookie, iPediaFields.transactionId,
            iPediaFields.regCodeValid
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.regCodeValid, 0)

    def test_InvalidProtocolVer(self):
        self.req = Request(protocolVer="2")
        self.req.addCookie()
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidProtocolVersion)

    def test_ClientInfoMalformed(self):
        self.req = Request("1", None)
        self.getResponse([iPediaFields.error])
        self.assertError(ServerErrors.requestArgumentMissing)

    def test_ClientInfoMissing(self):
        self.req = Request()
        self.req.clearFields()
        self.req.addTransactionId()
        self.req.addField(iPediaFields.protocolVersion, "1")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_ProtocolMissing(self):
        self.req = Request()
        self.req.clearFields()
        self.req.addTransactionId()
        self.req.addField(iPediaFields.clientInfo, "Python test client 1.0")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_InvalidCookie(self):
        # this is guaranteed to be an invalid cookie
        self.req = Request()
        self.req.addField(iPediaFields.cookie, "baraba")
        self.getResponse([iPediaFields.error, iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidCookie)

    def test_Random(self):
        self.req = getRequestHandleCookie(iPediaFields.getRandom, None)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.articleTitle, iPediaFields.formatVersion
        ])

    def test_GetSeattle(self):
        title = "seattle"
        self.req = getRequestHandleCookie(iPediaFields.getArticle, title)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.formatVersion, iPediaFields.articleBody,
            iPediaFields.articleTitle, iPediaFields.reverseLinks
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.formatVersion,
                              DEFINITION_FORMAT_VERSION)

    # TODO: doesn't work yet since we need to have a user with this reg_code
    # we either have to pre-create a test user or register a user from here
    def disable_test_GetSeattleWithValidRegcode(self):
        title = "seattle"
        self.req = Request()
        self.req.addField(iPediaFields.getArticle, title)
        self.req.addField(iPediaFields.regCode, testValidRegCode)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.articleBody,
            iPediaFields.articleTitle, iPediaFields.reverseLinks,
            iPediaFields.formatVersion
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.formatVersion,
                              DEFINITION_FORMAT_VERSION)

    def test_NotFound(self):
        # Ok, so I can't really guarantee that a article with this title doesn't exist
        # but this is a really good guess
        self.req = getRequestHandleCookie(
            iPediaFields.getArticle, "asdfasdflkj324;l1kjasd13214aasdf341l324")
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.notFound
        ])

    def test_SearchSeattle(self):
        searchTerm = "seattle"
        self.req = getRequestHandleCookie(iPediaFields.search, searchTerm)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.articleTitle, iPediaFields.searchResults
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.articleTitle, searchTerm)
        count = searchResultsCount(
            self.rsp.getField(iPediaFields.searchResults))
        #print "search result count: '%d'" % count
        # hard to establish the exact number but 100 should be good (when checked
        # for 7-7-2004 database, it was 201
        self.assertEqual(count > 100, True)

    def test_SearchNotFound(self):
        searchTerm = "asdfasdflkj324;l1kjasd13214aasdf341l324"
        self.req = getRequestHandleCookie(iPediaFields.search, searchTerm)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.notFound
        ])

    def test_GetArticleCount(self):
        self.req = getRequestHandleCookie(iPediaFields.getArticleCount, None)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.articleCount
        ])
        count = int(self.rsp.getField(iPediaFields.articleCount))
        # hard to guarantee to always have 100.000 but should be true given that
        # on 7-7-2004 it was 300.000+
        self.assertEqual(count > 100000, True)

    def test_GetDatabaseTime(self):
        self.req = getRequestHandleCookie(iPediaFields.getDatabaseTime, None)
        self.getResponse([
            iPediaFields.transactionId, iPediaFields.cookie,
            iPediaFields.databaseTime
        ])
        # date is in format YYYYMMDD
        date = self.rsp.getField(iPediaFields.databaseTime)
        assert 8 == len(date)

    def test_GetCookieGivesCookie(self):
        self.req = getRequestHandleCookie(iPediaFields.cookie, "I'm a cookie")
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    def test_GetCookieGivesRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.regCode,
                                          testValidRegCode)
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    def reqWithCookie(self, fieldName, fieldValue):
        self.req = getRequestHandleCookie(fieldName, fieldValue)

    def test_DuplicateField(self):
        self.req = getRequestHandleCookie(iPediaFields.getArticleCount, None)
        self.req.addField(iPediaFields.getArticleCount, None)
        self.getResponse([iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_VerifyRegCodeAsFirstRequest(self):
        # this is what client sends when it sends Verify-Register-Code
        # as the first request ever
        self.req = Request()
        self.req.addField(iPediaFields.getArticleCount, None)
        self.req.addField(iPediaFields.getDatabaseTime, None)
        self.req.addField(iPediaFields.verifyRegCode, testValidRegCode)
        self.req.addField(iPediaFields.getCookie, g_exampleDeviceInfo)
        self.getResponse([
            iPediaFields.cookie, iPediaFields.transactionId,
            iPediaFields.regCodeValid
        ])
        self.assertFieldEqual(self.rsp, iPediaFields.regCodeValid, 1)

    # verify that server rejects a query with both iPediaFields.cookie and iPediaFields.getCookie
    def test_GetCookieAndCookie(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_exampleDeviceInfo)
        self.getResponse([iPediaFields.cookie, iPediaFields.transactionId])
        cookie = self.rsp.getField(iPediaFields.cookie)
        self.req = Request()
        self.req.addField(iPediaFields.cookie, cookie)
        self.req.addField(iPediaFields.getCookie, g_exampleDeviceInfo)
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    # verify that server rejects a query with both iPediaFields.regCode and iPediaFields.getCookie
    def test_GetCookieAndRegCode(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_exampleDeviceInfo)
        self.req.addField(iPediaFields.regCode, testValidRegCode)
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    # test that server re-assigns the same cookie if we have a unique device info
    def test_DoubleRegistrationUniqueDeviceInfo(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_uniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId, iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_uniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId, iPediaFields.cookie])
        cookie2 = self.rsp.getField(iPediaFields.cookie)
        self.assertEqual(cookie, cookie2)

    # test that unregistered user reaches lookup limits
    def test_LookupLimitSearch(self):
        searchTerms = ["brazil", "seattle", "poland", "comedy"]
        # make sure to get a unique cookie, to start over
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_nonUniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId, iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        lookupsToDo = g_unregisteredLookupsLimit + 10
        for t in range(lookupsToDo):
            searchTerm = searchTerms[t % len(searchTerms)]
            self.req = Request()
            self.req.addField(iPediaFields.cookie, cookie)
            self.req.addField(iPediaFields.getArticle, searchTerm)
            self.getResponse([iPediaFields.transactionId])
            if self.rsp.hasField(iPediaFields.error):
                self.assertError(ServerErrors.lookupLimitReached)
                self.assertEqual(t, g_unregisteredLookupsLimit)
                return
            else:
                self.assertEqual(True,
                                 self.rsp.hasField(iPediaFields.articleTitle))
                self.assertEqual(True,
                                 self.rsp.hasField(iPediaFields.articleBody))
                self.assertEqual(True,
                                 self.rsp.hasField(iPediaFields.formatVersion))
                self.assertFieldEqual(self.rsp, iPediaFields.formatVersion,
                                      DEFINITION_FORMAT_VERSION)
        # didn't find response with an error so far, so there's a bug in the server
        self.assertEqual(True, False)

    # test that our server does unlocked version properly
    def test_NoLookupLimitInUnlockedVersion(self):
        searchTerms = ["brazil", "seattle", "poland", "comedy"]
        # make sure to get a unique cookie, to start over
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, g_nonUniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId, iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        lookupsToDo = g_unregisteredLookupsLimit + 10
        for t in range(lookupsToDo):
            searchTerm = searchTerms[t % len(searchTerms)]
            self.req = Request()
            self.req.addField(iPediaFields.cookie, cookie)
            self.req.addField(iPediaFields.getArticleU, searchTerm)
            self.getResponse([iPediaFields.transactionId])
            self.assertEqual(True,
                             self.rsp.hasField(iPediaFields.articleTitle))
            self.assertEqual(True, self.rsp.hasField(iPediaFields.articleBody))
            self.assertEqual(True,
                             self.rsp.hasField(iPediaFields.formatVersion))
            self.assertFieldEqual(self.rsp, iPediaFields.formatVersion,
                                  DEFINITION_FORMAT_VERSION)

    def test_InvalidDeviceInfo(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, "PL:blaha")
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.unsupportedDevice)

    def test_InvalidDeviceInfo2(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie, "PL:blaha")
        self.req.addField(iPediaFields.getArticle, "seattle")
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.unsupportedDevice)

    def test_InvalidLang(self):
        self.reqWithCookie(iPediaFields.useLang, "invalidLang")
        self.req.addField(iPediaFields.getArticleCount, None)
        self.getResponse([iPediaFields.transactionId, iPediaFields.error])
        self.assertError(ServerErrors.langNotAvailable)

    def test_availableLangs(self):
        self.reqWithCookie(iPediaFields.getAvailableLangs, None)
        self.getResponse(
            [iPediaFields.transactionId, iPediaFields.availableLangs])
        self.assertEqual("en de fr",
                         self.rsp.getField(iPediaFields.availableLangs))

    # verify that a registered user doesn't trigger lookup limits
    def test_RegisteredNoLookupLimits(self):
        # TODO:
        pass
Ejemplo n.º 5
0
 def getResponse(self,requiredFields=[]):
     self.rsp = Response(self.req)
     self.assertFieldsExist(self.rsp,requiredFields)
     if self.rsp.hasField(iPediaFields.transactionId):
         self.assertEqual(self.rsp.getField(iPediaFields.transactionId), self.req.transactionId)
Ejemplo n.º 6
0
class ServerTests(unittest.TestCase):

    def assertFieldExists(self,response,field):
        if not response.hasField(field):
            print "\nfield '%s' doesn't exist in response" % field
            print "all fields: %s" % string.join(response.getFields(),",")
            if response.hasField(iPediaFields.error):
                print "Error: %s" % response.getField(iPediaFields.error)
        self.assertEqual(response.hasField(field),True)

    def assertFieldDoesntExist(self,response,field):
        if response.hasField(field):
            print "\nfield '%s' exist in response" % field
            print "all fields: %s" % string.join(response.getFields(),",")
        self.assertEqual(response.hasField(field),False)

    def assertFieldsDontExist(self,response,fields):
        for field in fields:
            self.assertFieldDoesntExist(response,field)

    def assertFieldsExist(self,response,fields):
        for field in fields:
            self.assertFieldExists(response,field)

    def assertFieldEqual(self,response,field,value):
        # all values returned by server are strings. If value to compare with
        # is int, change it to string. This makes it easier to e.g. compare
        # server errors
        if isinstance(value,int):
            value = "%d" % value
        self.assertEqual(response.getField(field),value)

    def getResponse(self,requiredFields=[]):
        self.rsp = Response(self.req)
        self.assertFieldsExist(self.rsp,requiredFields)
        if self.rsp.hasField(iPediaFields.transactionId):
            self.assertEqual(self.rsp.getField(iPediaFields.transactionId), self.req.transactionId)

    def assertError(self,expectedError):
        self.assertFieldEqual(self.rsp, iPediaFields.error, expectedError)

    def test_Ping(self):
        # this is the simplest valid requests - only sends transaction id
        # in response server sends the same transaction id
        self.req = getRequestHandleCookie()
        self.getResponse([iPediaFields.cookie,iPediaFields.transactionId])

    def test_MalformedRequest(self):
        self.req = getRequestHandleCookie()
        # malformed, because there is no ":"
        self.req.addLine("malformed\n")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_MissingArgument(self):
        self.req = getRequestHandleCookie()
        # Get-Cookie requires an argument but we're not sending it
        self.req.addField(iPediaFields.getCookie, None)
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.requestArgumentMissing)

    def test_ExtraArgument(self):
        self.req = getRequestHandleCookie()
        # Get-Random-Article doesn't require an argument, but we're sending it
        self.req.addField(iPediaFields.getRandom, "not needed")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.unexpectedRequestArgument)

    def verifyArgument(self, field, fRequiresArguments):
        self.req = getRequestHandleCookie()
        # do the exact opposite of what's expected
        if fRequiresArguments:
            self.req.addField(field, None)
        else:
            self.req.addField(field, "not needed argument")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        if fRequiresArguments:
            self.assertError(ServerErrors.requestArgumentMissing)
        else:
            self.assertError(ServerErrors.unexpectedRequestArgument)
        
    # check if server correctly detects missing extra arguments
    def test_ArgumentsWithoutValue(self):
        fieldsWithoutValue = [iPediaFields.getRandom, iPediaFields.getArticleCount, iPediaFields.getDatabaseTime]
        for field in fieldsWithoutValue:
            self.verifyArgument(field,False)

    # check if server correctly detects missing arguments
    def test_ArgumentsWithValue(self):
        fieldsWithValue = [iPediaFields.protocolVersion, iPediaFields.clientInfo, iPediaFields.transactionId, iPediaFields.cookie, iPediaFields.getCookie, iPediaFields.getArticle, iPediaFields.regCode, iPediaFields.search, iPediaFields.verifyRegCode]
        for field in fieldsWithValue:
            self.verifyArgument(field,True)

    def test_UnrecognizedField(self):
        self.req = getRequestHandleCookie("Foo", "blast")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidRequest)

    def test_VerifyValidRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.verifyRegCode, testValidRegCode)
        self.getResponse([iPediaFields.cookie,iPediaFields.transactionId,iPediaFields.regCodeValid])
        self.assertFieldEqual(self.rsp,iPediaFields.regCodeValid,1)

    def test_VerifyInvalidRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.verifyRegCode, invalidRegCodeNumber)
        self.getResponse([iPediaFields.cookie,iPediaFields.transactionId,iPediaFields.regCodeValid])
        self.assertFieldEqual(self.rsp,iPediaFields.regCodeValid,0)

    def test_InvalidProtocolVer(self):
        self.req = Request(protocolVer="2")
        self.req.addCookie()
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidProtocolVersion)

    def test_ClientInfoMalformed(self):
        self.req = Request("1", None)
        self.getResponse([iPediaFields.error])
        self.assertError(ServerErrors.requestArgumentMissing)

    def test_ClientInfoMissing(self):
        self.req = Request()
        self.req.clearFields()
        self.req.addTransactionId()
        self.req.addField(iPediaFields.protocolVersion,"1")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_ProtocolMissing(self):
        self.req = Request()
        self.req.clearFields()
        self.req.addTransactionId()
        self.req.addField(iPediaFields.clientInfo,"Python test client 1.0")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_InvalidCookie(self):
        # this is guaranteed to be an invalid cookie
        self.req = Request()
        self.req.addField(iPediaFields.cookie,"baraba")
        self.getResponse([iPediaFields.error,iPediaFields.transactionId])
        self.assertError(ServerErrors.invalidCookie)

    def test_Random(self):
        self.req = getRequestHandleCookie(iPediaFields.getRandom, None)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.articleTitle,iPediaFields.formatVersion])

    def test_GetSeattle(self):
        title = "seattle"
        self.req = getRequestHandleCookie(iPediaFields.getArticle, title)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.formatVersion,iPediaFields.articleBody,iPediaFields.articleTitle,iPediaFields.reverseLinks])
        self.assertFieldEqual(self.rsp, iPediaFields.formatVersion, DEFINITION_FORMAT_VERSION)

    # TODO: doesn't work yet since we need to have a user with this reg_code
    # we either have to pre-create a test user or register a user from here
    def disable_test_GetSeattleWithValidRegcode(self):
        title = "seattle"
        self.req = Request()
        self.req.addField(iPediaFields.getArticle,title)
        self.req.addField(iPediaFields.regCode,testValidRegCode)
        self.getResponse([iPediaFields.transactionId,iPediaFields.articleBody,iPediaFields.articleTitle,iPediaFields.reverseLinks,iPediaFields.formatVersion])
        self.assertFieldEqual(self.rsp, iPediaFields.formatVersion, DEFINITION_FORMAT_VERSION)

    def test_NotFound(self):
        # Ok, so I can't really guarantee that a article with this title doesn't exist
        # but this is a really good guess
        self.req = getRequestHandleCookie(iPediaFields.getArticle, "asdfasdflkj324;l1kjasd13214aasdf341l324")
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.notFound])

    def test_SearchSeattle(self):
        searchTerm = "seattle"
        self.req = getRequestHandleCookie(iPediaFields.search, searchTerm)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.articleTitle,iPediaFields.searchResults])
        self.assertFieldEqual(self.rsp,iPediaFields.articleTitle,searchTerm)
        count = searchResultsCount(self.rsp.getField(iPediaFields.searchResults))
        #print "search result count: '%d'" % count
        # hard to establish the exact number but 100 should be good (when checked
        # for 7-7-2004 database, it was 201
        self.assertEqual(count > 100,True)

    def test_SearchNotFound(self):
        searchTerm = "asdfasdflkj324;l1kjasd13214aasdf341l324"
        self.req = getRequestHandleCookie(iPediaFields.search, searchTerm)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.notFound])

    def test_GetArticleCount(self):
        self.req = getRequestHandleCookie(iPediaFields.getArticleCount, None)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.articleCount])
        count = int(self.rsp.getField(iPediaFields.articleCount))
        # hard to guarantee to always have 100.000 but should be true given that
        # on 7-7-2004 it was 300.000+
        self.assertEqual(count>100000,True)

    def test_GetDatabaseTime(self):
        self.req = getRequestHandleCookie(iPediaFields.getDatabaseTime, None)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie,iPediaFields.databaseTime])
        # date is in format YYYYMMDD
        date = self.rsp.getField(iPediaFields.databaseTime)
        assert 8==len(date)

    def test_GetCookieGivesCookie(self):
        self.req = getRequestHandleCookie(iPediaFields.cookie, "I'm a cookie")
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    def test_GetCookieGivesRegCode(self):
        self.req = getRequestHandleCookie(iPediaFields.regCode, testValidRegCode)
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    def reqWithCookie(self,fieldName,fieldValue):
        self.req = getRequestHandleCookie(fieldName,fieldValue)

    def test_DuplicateField(self):
        self.req = getRequestHandleCookie(iPediaFields.getArticleCount, None)
        self.req.addField(iPediaFields.getArticleCount, None)
        self.getResponse([iPediaFields.transactionId])
        self.assertError(ServerErrors.malformedRequest)

    def test_VerifyRegCodeAsFirstRequest(self):
        # this is what client sends when it sends Verify-Register-Code
        # as the first request ever
        self.req = Request()
        self.req.addField(iPediaFields.getArticleCount, None)
        self.req.addField(iPediaFields.getDatabaseTime, None)
        self.req.addField(iPediaFields.verifyRegCode, testValidRegCode)
        self.req.addField(iPediaFields.getCookie, g_exampleDeviceInfo)
        self.getResponse([iPediaFields.cookie,iPediaFields.transactionId,iPediaFields.regCodeValid])
        self.assertFieldEqual(self.rsp,iPediaFields.regCodeValid,1)

    # verify that server rejects a query with both iPediaFields.cookie and iPediaFields.getCookie
    def test_GetCookieAndCookie(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_exampleDeviceInfo)
        self.getResponse([iPediaFields.cookie,iPediaFields.transactionId])
        cookie = self.rsp.getField(iPediaFields.cookie)
        self.req = Request()
        self.req.addField(iPediaFields.cookie,cookie)
        self.req.addField(iPediaFields.getCookie,g_exampleDeviceInfo)
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    # verify that server rejects a query with both iPediaFields.regCode and iPediaFields.getCookie
    def test_GetCookieAndRegCode(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_exampleDeviceInfo)
        self.req.addField(iPediaFields.regCode,testValidRegCode)
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.malformedRequest)

    # test that server re-assigns the same cookie if we have a unique device info
    def test_DoubleRegistrationUniqueDeviceInfo(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_uniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_uniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie])
        cookie2 = self.rsp.getField(iPediaFields.cookie)
        self.assertEqual(cookie,cookie2)

    # test that unregistered user reaches lookup limits
    def test_LookupLimitSearch(self):
        searchTerms = ["brazil","seattle","poland","comedy"]
        # make sure to get a unique cookie, to start over
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_nonUniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        lookupsToDo = g_unregisteredLookupsLimit+10
        for t in range(lookupsToDo):
            searchTerm = searchTerms[t%len(searchTerms)]
            self.req = Request()
            self.req.addField(iPediaFields.cookie,cookie)
            self.req.addField(iPediaFields.getArticle, searchTerm)
            self.getResponse([iPediaFields.transactionId])
            if self.rsp.hasField(iPediaFields.error):
                self.assertError(ServerErrors.lookupLimitReached)
                self.assertEqual(t,g_unregisteredLookupsLimit)
                return
            else:
                self.assertEqual(True,self.rsp.hasField(iPediaFields.articleTitle))
                self.assertEqual(True,self.rsp.hasField(iPediaFields.articleBody))
                self.assertEqual(True,self.rsp.hasField(iPediaFields.formatVersion))
                self.assertFieldEqual(self.rsp, iPediaFields.formatVersion, DEFINITION_FORMAT_VERSION)
        # didn't find response with an error so far, so there's a bug in the server
        self.assertEqual(True,False)

    # test that our server does unlocked version properly
    def test_NoLookupLimitInUnlockedVersion(self):
        searchTerms = ["brazil","seattle","poland","comedy"]
        # make sure to get a unique cookie, to start over
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,g_nonUniqueDeviceInfo)
        self.getResponse([iPediaFields.transactionId,iPediaFields.cookie])
        cookie = self.rsp.getField(iPediaFields.cookie)
        lookupsToDo = g_unregisteredLookupsLimit+10
        for t in range(lookupsToDo):
            searchTerm = searchTerms[t%len(searchTerms)]
            self.req = Request()
            self.req.addField(iPediaFields.cookie,cookie)
            self.req.addField(iPediaFields.getArticleU, searchTerm)
            self.getResponse([iPediaFields.transactionId])
            self.assertEqual(True,self.rsp.hasField(iPediaFields.articleTitle))
            self.assertEqual(True,self.rsp.hasField(iPediaFields.articleBody))
            self.assertEqual(True,self.rsp.hasField(iPediaFields.formatVersion))
            self.assertFieldEqual(self.rsp, iPediaFields.formatVersion, DEFINITION_FORMAT_VERSION)

    def test_InvalidDeviceInfo(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,"PL:blaha")
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.unsupportedDevice)

    def test_InvalidDeviceInfo2(self):
        self.req = Request()
        self.req.addField(iPediaFields.getCookie,"PL:blaha")
        self.req.addField(iPediaFields.getArticle, "seattle")
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.unsupportedDevice)

    def test_InvalidLang(self):
        self.reqWithCookie(iPediaFields.useLang, "invalidLang")
        self.req.addField(iPediaFields.getArticleCount, None)
        self.getResponse([iPediaFields.transactionId,iPediaFields.error])
        self.assertError(ServerErrors.langNotAvailable)

    def test_availableLangs(self):
        self.reqWithCookie(iPediaFields.getAvailableLangs, None)
        self.getResponse([iPediaFields.transactionId, iPediaFields.availableLangs])
        self.assertEqual("en de fr", self.rsp.getField(iPediaFields.availableLangs))

    # verify that a registered user doesn't trigger lookup limits
    def test_RegisteredNoLookupLimits(self):
        # TODO:
        pass