示例#1
0
    def test_only_shows_right_trades(self):
        c = Client()
        garbagePlayers = [
            Player.objects.get(user=u) for u in self.otherUsers[:2]
        ]
        trade = createTrade(*garbagePlayers, self.testFloor)
        trade.save()

        otherGarbagePlayers = [
            Player.objects.get(user=u) for u in self.otherUsers[2:4]
        ]
        otherTrade = createTrade(*otherGarbagePlayers, self.testFloor)
        otherPlayer = Player.objects.get(user=self.otherUsers[5])
        otherTrade.sender = otherPlayer
        otherTrade.senderStocks.clear()
        otherTrade.senderStocks.add(otherPlayer.stocks.all().first())

        playerWithTrade = trade.sender
        sessionId = SessionId(associated_user=playerWithTrade.user)
        sessionId.save()
        response = c.get(reverseWithSession("viewAllTrades", sessionId))
        returnedTrades = [
            Trade.objects.get(pk=i["id"])
            for i in loads(response.content.decode("UTF-8"))
        ]
        for i in returnedTrades:
            self.assertTrue(i.sender == playerWithTrade
                            or i.recipient == playerWithTrade)
示例#2
0
    def test_create_suggestion(self):
        c = Client()
        u = User.objects.create_user(username=USERNAME, password=PASSWORD)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        randomFloor = self.testFloor
        randomFloor.permissiveness = "permissive"
        randomFloor.save()
        stockToSuggest = Stock(symbol="SF")
        stockToSuggest.save()
        player = Player(floor=randomFloor, user=u)
        player.save()

        data = {}
        data["stock"] = stockToSuggest.pk
        data["requestingPlayer"] = player.pk
        data["floor"] = randomFloor.pk
        response = c.post(reverseWithSession("createStockSuggestion",
                                             sessionId),
                          dumps(data),
                          content_type="application/json")
        jsonObj = loads(response.content.decode("UTF-8"))
        newSuggestion = StockSuggestion.objects.get(pk=jsonObj["id"])
        self.assertEquals(newSuggestion.stock, stockToSuggest)
        self.assertEquals(newSuggestion.requesting_player, player)
        self.assertEquals(newSuggestion.floor, randomFloor)
示例#3
0
    def test_no_user_breaks_trade(self):
        """
        Make sure than an unauthenticated user can't read trades
        """

        c = Client()
        response = c.get(reverse("viewAllTrades"))
        self.assertTrue("error" in response.content.decode("UTF-8"))

        garbagePlayers = [
            Player.objects.get(user=u) for u in self.otherUsers[:2]
        ]
        randomTrade = createTrade(*garbagePlayers, self.testFloor)
        randomTrade.save()

        response = c.get(reverse("viewTrade", args=(randomTrade.pk, )))
        self.assertTrue("error" in response.content.decode("UTF-8"))

        otherPlayer = Player.objects.all(). \
            exclude(pk=randomTrade.sender.pk). \
            exclude(pk=randomTrade.recipient.pk). \
            filter(floor=randomTrade.floor).first()

        id = SessionId(associated_user=otherPlayer.user)
        id.save()

        response = c.get(
            reverseWithSession("viewTrade", id, args=(randomTrade.pk, )))
        self.assertTrue("error" in response.content.decode("UTF-8"))
示例#4
0
    def test_decline_trade(self):
        floor = self.testFloor
        player1 = Player.objects.get(user=self.otherUsers[1], floor=floor)
        player2 = Player.objects.get(user=self.otherUsers[2], floor=floor)
        trade = createTrade(player1, player2, floor)
        sender = trade.sender
        recipient = trade.recipient
        originalSenderStocks = list(sender.stocks.all())
        originalRecipientStocks = list(recipient.stocks.all())
        trade.senderStocks = originalSenderStocks
        trade.recipientStocks = originalRecipientStocks
        trade.save()

        sessionId = SessionId(associated_user=recipient.user)
        sessionId.save()

        c = Client()
        response = c.post(
            reverseWithSession("declineTrade", sessionId, args=(trade.pk, )))
        self.assertTrue("success" in response.content.decode("UTF-8"))

        try:
            Trade.objects.get(pk=trade.pk)
            self.fail()
        except ObjectDoesNotExist:
            pass

        sender.refresh_from_db()
        recipient.refresh_from_db()

        self.assertEquals(set(sender.stocks.all()), set(originalSenderStocks))
        self.assertEquals(set(recipient.stocks.all()),
                          set(originalRecipientStocks))
示例#5
0
    def test_create_floor(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        floorName = "Four on the Floor"
        data = {}
        data["name"] = floorName
        data["permissiveness"] = "Permissive"
        data["owner"] = u.pk
        data["public"] = True
        data["numStocks"] = 10
        data["stocks"] = [s.pk for s in Stock.objects.all()[:15]]

        response = c.post(reverseWithSession("ApiCreateFloor", sessionId),
                          dumps(data),
                          content_type="application/json")

        jsonObj = loads(response.content.decode("UTF-8"))
        newFloor = Floor.objects.get(pk=jsonObj["id"])
        self.assertEquals(floorName, newFloor.name)
        self.assertEquals(data["permissiveness"], newFloor.permissiveness)
        self.assertEquals(data["owner"], newFloor.owner.pk)

        self.assertDictEqual(
            {
                i: True
                for i in map(lambda x: Stock.objects.get(pk=x), data["stocks"])
            }, {i: True
                for i in newFloor.stocks.all()})
示例#6
0
    def test_reject_suggestion(self):
        randomFloor = self.testFloor
        randomStock = Stock(symbol="SF")
        randomStock.save()
        u = User.objects.create_user(username=USERNAME, password=PASSWORD)
        player = Player(floor=randomFloor, user=u)
        player.save()
        suggestion = StockSuggestion(stock=randomStock,
                                     floor=randomFloor,
                                     requesting_player=player)
        suggestion.save()

        sessionId = SessionId(associated_user=randomFloor.owner)
        sessionId.save()

        c = Client()
        response = c.post(
            reverseWithSession("rejectStockSuggestion",
                               sessionId,
                               args=(suggestion.pk, )))
        self.assertTrue("success" in response.content.decode("UTF-8"))

        try:
            StockSuggestion.objects.get(pk=suggestion.pk)
            self.fail()
        except ObjectDoesNotExist:
            pass

        randomFloor.refresh_from_db()
        self.assertFalse(randomStock in randomFloor.stocks.all())
示例#7
0
    def test_bad_create_floor(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        floorName = "Four on the Floor"
        idealData = {}
        idealData["name"] = floorName
        idealData["permissiveness"] = "Permissive"
        idealData["owner"] = u.pk
        idealData["public"] = True
        idealData["numStocks"] = 10
        idealData["stocks"] = [s.pk for s in Stock.objects.all()[:15]]

        # Test empty stocks on closed floor
        data = idealData.copy()
        data["permissiveness"] = "Closed"
        data["stocks"] = []
        response = c.post(reverseWithSession("ApiCreateFloor", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # User tries to create floor as someone else
        data = idealData.copy()
        data["owner"] = User.objects.all().exclude(pk=u.pk).first().pk
        response = c.post(reverseWithSession("ApiCreateFloor", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Miss stuff
        data = idealData.copy()
        del data["numStocks"]
        response = c.post(reverseWithSession("ApiCreateFloor", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Pass a floorPlayer
        floorPlayer = Player(user=u, floor=Floor.objects.all().first())
        floorPlayer.save()
        data = idealData.copy()
        data["floorPlayer"] = floorPlayer.pk

        response = c.post(reverseWithSession("ApiCreateFloor", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))
示例#8
0
 def test_view_one_player(self):
     c = Client()
     player1 = Player.objects.get(user=self.otherUsers[0])
     player2 = Player.objects.get(user=self.otherUsers[1])
     trade = createTrade(player1, player2, self.testFloor)
     for p in Player.objects.all():
         session = SessionId(associated_user=p.user)
         session.save()
         response = c.get(
             reverseWithSession("viewPlayer", session, args=(p.pk, )))
         self.assertEquals(
             loads(response.content.decode("UTF-8")),
             loads(JsonResponse(p.toJSON()).content.decode("UTF-8")))
示例#9
0
    def test_bad_create_player(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        data = {}
        floor = Floor.objects.all().first()
        data["user"] = u.pk
        data["floor"] = floor.pk

        # Test no session
        response = c.post(reverse("createPlayer"),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test wrong session
        otherUser = User.objects.create_user(username=username + "1",
                                             password=password)
        otherSessionId = SessionId(associated_user=otherUser)
        response = c.post(reverseWithSession("createPlayer", otherSessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test data that it shouldn't get
        data["points"] = 52
        response = c.post(reverseWithSession("createPlayer", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))
        del data["points"]

        # Test creating player that already exists on floor
        player = Player(floor=floor, user=u)
        player.save()
        response = c.post(reverseWithSession("createPlayer", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))
        player.delete()

        # Test missing data
        del data["user"]
        response = c.post(reverseWithSession("createPlayer", sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))
示例#10
0
    def test_bad_accept_trade(self):
        floor = self.testFloor
        player1 = Player.objects.get(user=self.otherUsers[1], floor=floor)
        player2 = Player.objects.get(user=self.otherUsers[2], floor=floor)
        trade = createTrade(player1, player2, floor)
        sender = trade.sender
        recipient = trade.recipient
        originalSenderStocks = list(sender.stocks.all())
        originalRecipientStocks = list(recipient.stocks.all())
        trade.senderStocks = originalSenderStocks
        trade.recipientStocks = originalRecipientStocks
        trade.save()

        sessionId = SessionId(associated_user=recipient.user)
        sessionId.save()

        c = Client()

        # No user
        response = c.post(reverse("acceptTrade", args=(trade.pk, )))
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Wrong user
        badSessionId = SessionId(associated_user=sender.user)
        badSessionId.save()
        response = c.post(
            reverseWithSession("acceptTrade", badSessionId, args=(trade.pk, )))
        self.assertTrue("error" in response.content.decode("UTF-8"))
示例#11
0
    def test_all_players_blocks_trades(self):
        c = Client()
        player1 = Player.objects.get(user=self.otherUsers[0])
        player2 = Player.objects.get(user=self.otherUsers[1])

        trade = createTrade(player1, player2, self.testFloor)
        response = c.get(reverse("viewAllPlayers"))
        jsonObj = loads(response.content.decode("UTF-8"))
        for i in jsonObj:
            self.assertFalse(i["sentTrades"])
            self.assertFalse(i["receivedTrades"])

        session = SessionId(associated_user=player1.user)
        session.save()

        response = c.get(reverseWithSession("viewAllPlayers", session))
        jsonObj = loads(response.content.decode("UTF-8"))

        # Make sure the user can see trades for himself and himself only
        for i in jsonObj:
            if i["id"] != player1.id:
                self.assertFalse([
                    i for i in i["sentTrades"]
                    if not tradeInvolvesUser(Trade.objects.get(
                        pk=i["id"]), player1.user)
                ])
                self.assertFalse([
                    i for i in i["receivedTrades"]
                    if not tradeInvolvesUser(Trade.objects.get(
                        pk=i["id"]), player1.user)
                ])

                self.assertEquals([
                    i for i in i["sentTrades"]
                    if tradeInvolvesUser(Trade.objects.get(
                        pk=i["id"]), player1.user)
                ], i["sentTrades"])
                self.assertEquals([
                    i for i in i["receivedTrades"]
                    if tradeInvolvesUser(Trade.objects.get(
                        pk=i["id"]), player1.user)
                ], i["receivedTrades"])
            else:
                self.assertEquals(len(i["sentTrades"]),
                                  Trade.objects.filter(sender=player1).count())

                self.assertEquals(
                    len(i["receivedTrades"]),
                    Trade.objects.filter(recipient=player1).count())
示例#12
0
    def test_register_token(self):
        user = User.objects.create_user(username=USERNAME, password=PASSWORD)
        sessionId = SessionId(associated_user=user)
        sessionId.save()
        c = Client()
        old_len = AndroidToken.objects.filter(user=user).count()
        response = c.post(
            reverseWithSession("registerToken", sessionId),
            dumps({"registrationToken": AndroidTests.FAKE_ANDROID_ID}),
            content_type="application/json")

        tokens = AndroidToken.objects.filter(user=user)
        self.assertTrue(tokens.count() > old_len)
        newToken = tokens.first()
        self.assertEquals(newToken.token, AndroidTests.FAKE_ANDROID_ID)
示例#13
0
def getToken(request):
    post = loads(request.body.decode("UTF-8"))
    if not (post.get('username', None) and post.get('password', None)):
        return getParamError()
    username = post["username"]
    password = post["password"]
    try:
        user = User.objects.get(username=username)
    except ObjectDoesNotExist:
        return JsonResponse({"error": "That username doesn't exist"})

    if not user.check_password(password):
        return JsonResponse({"error": "That password is wrong"})

    newSessionId = SessionId(associated_user=user)
    newSessionId.save()
    return JsonResponse({"sessionId": newSessionId.id_string, "user": userJSON(user)})
示例#14
0
 def test_hides_private_floors(self):
     c = Client()
     user = User.objects.all().first()
     privateFloor = Floor(name="hiddenFloor",
                          permissiveness="open",
                          owner=user,
                          public=False)
     privateFloor.save()
     response = c.get(reverse("viewAllFloors"))
     floors = map(lambda x: Floor.objects.get(pk=x["id"]),
                  loads(response.content.decode("UTF-8")))
     for f in floors:
         self.assertTrue(f.public)
     # Test shows private floors that user is on
     sessionId = SessionId(associated_user=user)
     sessionId.save()
     response = c.get(reverseWithSession("viewAllFloors", sessionId))
     self.assertTrue(
         privateFloor.pk in
         [f["id"] for f in loads(response.content.decode("UTF-8"))])
示例#15
0
    def test_create_player(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        data = {}
        floor = Floor.objects.all().first()
        data["user"] = u.pk
        data["floor"] = floor.pk
        response = c.post(reverseWithSession("createPlayer", sessionId),
                          dumps(data),
                          content_type="application/json")

        returnedPlayer = Player.objects.get(floor=floor, user=u)
        self.assertEquals(
            loads(response.content.decode("UTF-8")),
            loads(
                JsonResponse(returnedPlayer.toJSON(),
                             safe=False).content.decode("UTF-8")))
示例#16
0
    def test_create_trade(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        floor = self.testFloor

        player1 = Player(user=u, floor=floor)
        player1.save()
        stocksToReturn = list(player1.stocks.all())
        assert len(stocksToReturn) == 0

        player2 = Player.objects.get(floor=floor, user=self.otherUsers[2])
        stocksToSend = list(player2.stocks.all())

        data = {}
        data["senderPlayer"] = player1.pk
        data["senderStocks"] = tuple(map(lambda x: x.pk, stocksToReturn))

        data["recipientPlayer"] = player2.pk
        data["recipientStocks"] = tuple(map(lambda x: x.pk, stocksToSend))

        data["floor"] = floor.pk

        response = c.post(reverseWithSession("createTrade", sessionId),
                          dumps(data),
                          content_type="application/json")
        jsonObj = loads(response.content.decode("UTF-8"))
        returnedTrade = Trade.objects.get(pk=jsonObj["id"])
        self.assertEquals(
            jsonObj,
            loads(
                JsonResponse(returnedTrade.toJSON(),
                             safe=False).content.decode("UTF-8")))
示例#17
0
    def test_stock_suggestions_only_shows_to_owner(self):
        c = Client()
        response = c.get(reverse("viewAllStockSuggestions"))
        self.assertTrue("error" in response.content.decode("UTF-8"))

        permissiveFloor = self.testFloor
        permissiveFloor.permissiveness = "permissive"
        permissiveFloor.save()
        owner = permissiveFloor.owner
        newStock = Stock(symbol="SF")
        newStock.save()
        goodSuggestion = StockSuggestion(
            stock=newStock,
            floor=self.testFloor,
            requesting_player=Player.objects.filter(
                floor=self.testFloor).exclude(user=owner).first())
        goodSuggestion.save()
        goodSessionId = SessionId(associated_user=owner)
        goodSessionId.save()

        badUser = User.objects.create_user(username="******",
                                           password="******")
        badSessionId = SessionId(associated_user=badUser)
        badSessionId.save()

        response = c.get(
            reverseWithSession("viewStockSuggestion",
                               badSessionId,
                               args=(goodSuggestion.pk, )))
        self.assertTrue("error" in response.content.decode("UTF-8"))

        response = c.get(
            reverseWithSession("viewStockSuggestion",
                               goodSessionId,
                               args=(goodSuggestion.pk, )))
        self.assertEquals(
            loads(response.content.decode("UTF-8")),
            loads(
                JsonResponse(goodSuggestion.toJSON()).content.decode("UTF-8")))
示例#18
0
    def test_bad_create_suggestion(self):
        c = Client()
        u = User.objects.create_user(username=USERNAME, password=PASSWORD)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        randomFloor = self.testFloor
        randomFloor.permissiveness = "permissive"
        randomFloor.save()

        stockToSuggest = Stock(symbol="SF")
        stockToSuggest.save()

        player = Player(floor=randomFloor, user=u)
        player.save()

        idealData = {}
        idealData["stock"] = stockToSuggest.pk
        idealData["requestingPlayer"] = player.pk
        idealData["floor"] = randomFloor.pk

        # Test missing data
        data = idealData.copy()
        del data["stock"]
        response = c.post(reverseWithSession("createStockSuggestion",
                                             sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test wrong sessionId
        data = idealData.copy()
        badUser = Player.objects.filter(floor=randomFloor).exclude(
            pk=player.pk).first().user
        badSession = SessionId(associated_user=badUser)
        badSession.save()
        response = c.post(reverseWithSession("createStockSuggestion",
                                             badSession),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test wrong floor
        data = idealData.copy()
        differentFloor = createFloor(self.otherUsers[1])
        differentFloor.save()
        requestingPlayer = Player.objects.filter(floor=differentFloor).first()
        data["requestingPlayer"] = requestingPlayer.pk
        otherSession = SessionId(associated_user=requestingPlayer.user)
        otherSession.save()
        response = c.post(reverseWithSession("createStockSuggestion",
                                             otherSession),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test stock already on floor
        data = idealData.copy()
        badStock = randomFloor.stocks.all().first()
        data["stock"] = badStock.pk
        response = c.post(reverseWithSession("createStockSuggestion",
                                             sessionId),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Test not permissive floor
        data = idealData.copy()
        badFloor = Floor.objects.all().exclude(
            permissiveness="permissive").first()
        p = Player.objects.filter(floor=badFloor).first()
        s = Stock.objects.all().exclude(
            pk__in=map(lambda s: s.pk, p.floor.stocks.all())).first()
        data["floor"] = badFloor.pk
        data["requestingPlayer"] = p.pk
        data["stock"] = s.pk
        response = c.post(reverseWithSession("createStockSuggestion",
                                             badSession),
                          dumps(data),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))
示例#19
0
    def test_bad_create_trade(self):
        c = Client()
        username = "******"
        password = "******"
        u = User.objects.create_user(username=username, password=password)
        sessionId = SessionId(associated_user=u)
        sessionId.save()

        floor = self.testFloor

        player1 = Player(user=u, floor=floor)
        player1.save()
        stocksToReturn = list(player1.stocks.all())
        assert len(stocksToReturn) == 0

        player2 = Player.objects.get(floor=floor, user=self.otherUsers[2])
        stocksToSend = list(player2.stocks.all())

        idealData = {}
        idealData["senderPlayer"] = player1.pk
        idealData["senderStocks"] = tuple(map(lambda x: x.pk, stocksToReturn))

        idealData["recipientPlayer"] = player2.pk
        idealData["recipientStocks"] = tuple(map(lambda x: x.pk, stocksToSend))

        idealData["floor"] = floor.pk

        # Make sure the right data works
        response = c.post(reverseWithSession("createTrade", sessionId),
                          dumps(idealData),
                          content_type="application/json")
        jsonObj = loads(response.content.decode("UTF-8"))
        try:
            t = Trade.objects.get(pk=jsonObj["id"])
            t.delete()
        except ObjectDoesNotExist:
            self.assertTrue(False)

        # No sessionId
        response = c.post(reverse("createTrade"),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Wrong sessionId
        badUser = User.objects.create_user(username=username + "2",
                                           password=password)
        badSession = SessionId(associated_user=badUser)
        badSession.save()
        response = c.post(reverseWithSession("createTrade", badSession),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Missing data
        questionableData = idealData.copy()
        del questionableData["senderPlayer"]
        response = c.post(reverseWithSession("createTrade", badSession),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Bad stocks
        questionableData = idealData.copy()
        questionableData["senderStocks"] = []
        questionableData["recipientStocks"] = []
        response = c.post(reverseWithSession("createTrade", badSession),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        questionableData = idealData.copy()
        questionableData["senderStocks"], questionableData[
            "recipientStocks"] = questionableData[
                "recipientStocks"], questionableData["senderStocks"]
        response = c.post(reverseWithSession("createTrade", badSession),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))

        # Send date
        questionableData = idealData.copy()
        questionableData["date"] = datetime.utcnow().isoformat()
        response = c.post(reverseWithSession("createTrade", badSession),
                          dumps(idealData),
                          content_type="application/json")
        self.assertTrue("error" in response.content.decode("UTF-8"))