def test_show_room_users(self): '''Test GET server.show_room_users''' with self.client as test_client: room_name = "tesseract" user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user penny_penguin = User(user_name) db.session.add(penny_penguin) db.session.commit() # Add the user to the room new_room = Room.query.filter(Room.name == room_name).first() penny_penguin = User.query.filter(User.name == user_name).first() balloonicorn = User.query.get(1) anonymouse = User.query.get(2) # print type(balloonicorn), balloonicorn, balloonicorn.user_id # print type(anonymouse), anonymouse, anonymouse.user_id # db.session.add(main_room.join_room(anonymouse)) db.session.add(new_room.join_room(penny_penguin)) db.session.add(new_room.join_room(balloonicorn)) db.session.add(new_room.join_room(anonymouse)) db.session.commit() result = test_client.get( '/api/rooms/{}/users'.format(int(new_room.room_id))) # print "rooms and users:\n", result.data self.assertIn('"name": "{}",'.format( penny_penguin.name), result.data)
def test_show_room_users(self): '''Test GET server.show_room_users''' with self.client as test_client: room_name = "tesseract" user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user penny_penguin = User(user_name) db.session.add(penny_penguin) db.session.commit() # Add the user to the room new_room = Room.query.filter(Room.name == room_name).first() penny_penguin = User.query.filter(User.name == user_name).first() balloonicorn = User.query.get(1) anonymouse = User.query.get(2) # print type(balloonicorn), balloonicorn, balloonicorn.user_id # print type(anonymouse), anonymouse, anonymouse.user_id # db.session.add(main_room.join_room(anonymouse)) db.session.add(new_room.join_room(penny_penguin)) db.session.add(new_room.join_room(balloonicorn)) db.session.add(new_room.join_room(anonymouse)) db.session.commit() result = test_client.get('/api/rooms/{}/users'.format( int(new_room.room_id))) # print "rooms and users:\n", result.data self.assertIn('"name": "{}",'.format(penny_penguin.name), result.data)
def create_room(arg): game_info = Game.get(arg['game']['id']) room = Room(name=arg['name'], capacity=arg['capacity'], game=game_info, difficulty=arg['game']['difficulty']) room.put() return room
def test_room_equality(self): # Equality is true r2 = Room(self.polygon1.clone(), [t.clone() for t in self.room1.texts]) r3 = Room(self.polygon1.clone(), [t.clone() for t in self.room1.texts[1:]]) # Equality is false d = Room(self.polygon1.clone().traslate(1, 0), [t.clone() for t in self.room1.texts]) self.assertEqual(self.room1, r2) self.assertEqual(self.room1, r3) self.assertNotEqual(self.room1, d)
def rooms(): name = getPlayerName(request.authorization.username) if request.method == 'GET': # Layoutificator getting map data for graphical display if request.headers.get('Content-Type') == 'application/json': return jsonifyRooms(Room.getMy(name), Roomexit.getMy(name)) # List of rooms for individual editing else: return render_template("list.html", type='room', things=Room.getMy(name)) # Layoutificator sending map data elif request.method == 'POST': return sendRoomsToDb(request.json)
def test_floor_to_serializable(self): p2 = Polygon.from_absolute_coordinates([(12,0),(22,0),(22,10),(12,10)]) r2 = Room(p2) f = Floor("Building cool name","Floor cool name", [self.room1, r2]) self.assertEqual( f.to_serializable() , { "walls" : [], "windows" : [], "b_id" : f.b_id, "f_id" : f.f_id, "rooms" : [self.room1.to_serializable(), r2.to_serializable()] })
def test_room_encoding_and_decoding(self): r = Room([(1,2), (3, 4), (5, 6)]) self.room1.add_text(Text("Encoded cool text", Point([1,1]))) s1 = json.dumps(self.room1.to_serializable(), indent = 3) d1 = json.loads(s1) r2 = Room.from_serializable(d1) self.assertEqual(self.room1.polygon.points, r2.polygon.points) self.assertEqual(self.room1.texts, r2.texts) s2 = json.dumps(self.room1.to_serializable(), indent = 4) d2 = json.loads(s2) self.assertEqual(d1, d2)
def create_room(arg): assert arg['game'].has_key( 'map_size'), 'Required argument is missing: "game.map_size".' player = arg['sender'] game_info = Game.get(arg['game']['id']) room = Room(name=arg['name'], capacity=arg['capacity'], game=game_info, map_size=arg['game']['map_size']) room.put() player.room = room player.is_ready = True player.put() return {'room': str(player.room.key())}
def test_floor_to_serializable(self): p2 = Polygon.from_absolute_coordinates([(12, 0), (22, 0), (22, 10), (12, 10)]) r2 = Room(p2) f = Floor("Building cool name", "Floor cool name", [self.room1, r2]) self.assertEqual( f.to_serializable(), { "walls": [], "windows": [], "b_id": f.b_id, "f_id": f.f_id, "rooms": [self.room1.to_serializable(), r2.to_serializable()], }, )
def loadRooms(self): roomLoaded = filesUtils.loadFromFile('model/roomsOriginal.txt') if roomLoaded == None or len(roomLoaded) == 0: rooms = {} rooms['Geral'] = Room('Geral', None, [], {}) else: rooms = {} for name, dic in roomLoaded.items(): admin = dic['admin'] bans = list(dic['bans']) timeouts = dic['timeouts'] rooms[name.strip()] = Room( name.strip(), admin if admin == None else admin.strip(), bans, timeouts) return rooms
def check_if_db(room_id: Optional[int] = None, return_exits: bool = False) -> Tuple[int, List[str]]: """ checks if the current room you're in is in the database. if not, adds it. to be helpful, returns current room id if given an int, it will check that room. not not, it will initialize. """ sess = Session(bind=engine) if not room_id: i = init() sleep(i['cooldown']) room_id = i['room_id'] room_ = sess.query(Room).filter(Room.room_id==room_id) if not room_.all(): i = init() sleep(i['cooldown']) room = Room(room_id=room_id, title=i['title']) print('ADDING NEW ROOM ', end='') sess.add(room) sess.commit() if return_exits: try: return room_id, i['exits'] except NameError as e: i = init() sleep(i['cooldown']) return room_id, i['exits'] else: return room_id, []
def get_room(self, name): try: room = self.conference.rooms[name] except KeyError: room = Room(name) self.conference.rooms[name] = room return room
def test_show_all_rooms(self): room_name = "lalala" new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() result = self.client.get('/api/rooms') self.assertIn(result.data, '"name": "{}",'.format(room_name))
def main(): if len(sys.argv) == 2: map_name = sys.argv[1] else: exit(1) map_file = open(map_name, 'r') # ввод данных map_data = map_file.read() links = re.findall('\w+-\w+', map_data) rooms = re.findall('\w+ \d+ \d+', map_data) paths = re.findall('(L.*?)\n', map_data) print(paths) # парсинг данных на узлы, ребра и перемещения за каждый шаг rooms_dict = {} links_list = [] for room in rooms: buf = room.split(' ') rooms_dict[buf[0]] = (Room(buf[0], int(buf[1]) * ZOOM, int(buf[2]) * ZOOM, NODE_SIZE)) print(buf[0], buf[1], buf[2]) for link in links: buf = link.split('-') if not buf[0].startswith('L'): line = Link(None, None) for room in rooms_dict: room = rooms_dict[room] if room.name == buf[0]: line.start = room elif room.name == buf[1]: line.end = room links_list.append(line) start_room = re.findall('##start\n(\w+)', map_data)[0].split('\n')[0] moves_list = [] moved_ants = set() for path in paths: move_per_ant = ' ' + path move_per_ant = move_per_ant.split(' L') moves = {} for ant_move in move_per_ant: if ant_move != '': ant_move = ant_move.split('-') if not ant_move[0] in moved_ants: moved_ants.add(ant_move[0]) moves[ant_move[0]] = Move(rooms_dict[start_room], rooms_dict[ant_move[1]], ant_move[0]) else: previous_ant_move = moves_list[-1][ant_move[0]] moves[ant_move[0]] = Move(previous_ant_move.end, rooms_dict[ant_move[1]], ant_move[0]) moves_list.append(moves) game = Game(links_list, moves_list) game.run()
def test_create_room_users(self): '''Test POST server.show_room_users''' with self.client as test_client: room_name = "tesseract" user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user penny_penguin = User(user_name) db.session.add(penny_penguin) db.session.commit() # Add the user to the room new_room = Room.query.filter(Room.name == room_name).first() penny_penguin = User.query.filter(User.name == user_name).first() result_post_1 = test_client.post( '/api/rooms/{}/users'.format(int(new_room.room_id)), data={'user_id': penny_penguin.user_id}) # print "result_post_1:\n", result_post_1.data penny_penguin self.assertIn('"name": "{}",'.format(penny_penguin.name), result_post_1.data)
def create_room(room_name): room = Room(room_name=room_name) db.session.add(room) db.session.commit() return room
def insert(): name = ["John","Haifen","Dan","Morres","Issac","Vikas","Bill","Ross","Chandler"] team = ["API","Finance"] for i in xrange(1,37): seat = Seats() if i in [1,5]: seat.user = random.choice(name) seat.status = "Allocated" seat.teamname = team[0] if i in [10]: seat.user = random.choice(name) seat.status = "Allocated" seat.teamname = team[1] seat.building = 1 seat.floor = 1 seat.seatnum = i seat.row = i/9 if i%9==0 else i/9+1 seat.save() for i in xrange(1,7): room = Room() room.building = 1 room.floor = 1 room.roomnum = i room.save() return "done"
def enterRoom(self, user, msg): try: roomName = msg.split()[1] self.checkRoomAssocioate(user) if not roomName in self.rooms: room = Room(roomName, user.name, [], {}) self.rooms[roomName] = room self.userRooms[user].append(roomName) self.rooms[roomName].enterUser(user) self.saveRooms() elif not roomName in self.userRooms[user]: room = self.rooms[roomName] self.userRooms[user].append(roomName) room.enterUser(user) except IndexError: user.socket.sendall( JsonHandler.encode('#msg', 'tem que indicar o nome da sala').encode())
def __init__(self, cfg): self.name = cfg.get("class", "Unknown Class") self.assigned = {} self.allowed_rows = {} self.disallowed_rows = {} self.allowed_columns = {} self.disallowed_columns = {} self.separate = [] self.keep_near = [] self.counter = Counter() for kid in cfg["kids"]: name = kid["name"] self.counter[name] = 0 for k in kid.get("keep_away_from", []): ka = set([k, name]) self.counter[name] += 1 if ka not in self.separate: self.separate.append(ka) for k in kid.get("keep_near", []): self.counter[name] += 1 sn = set([k, name]) if sn not in self.keep_near: self.keep_near.append(sn) if "assigned" in kid: self.counter[name] += 1 self.assigned[name] = [x - 1 for x in kid["assigned"]] else: if "allowed_rows" in kid: self.counter[name] += len(kid["allowed_rows"]) self.allowed_rows[name] = [ x - 1 for x in kid["allowed_rows"] ] if "disallowed_rows" in kid: self.counter[name] += len(kid["disallowed_rows"]) self.disallowed_rows[name] = [ x - 1 for x in kid["disallowed_rows"] ] if "allowed_columns" in kid: self.counter[name] += len(kid["allowed_columns"]) self.allowed_columns[name] = [ x - 1 for x in kid["allowed_columns"] ] if "disallowed_columns" in kid: self.counter[name] += len(kid["disallowed_columns"]) self.disallowed_columns[name] = [ x - 1 for x in kid["disallowed_columns"] ] self.kids = [k[0] for k in self.counter.most_common()] self.room = Room(width=cfg["columns"], height=cfg["rows"])
def list_room(arg): return _format_message( 'list_room', 'ok', { 'rooms': [{ 'id': str(r.key()), 'name': r.name, 'game': r.game.title, 'remain_capacity': r.capacity - r.players.count() } for r in Room.all() if r.players.count() > 0] })
def create_room(data): name = data['name'] if name in rooms: status = "There is already a room with that name" emit('failure', status, broadcast=False) else: room = Room(title=name, made_by=session['name']) rooms[name] = room room = room.__dict__ emit('show rooms', room, broadcast=True)
def setUp(self): # 10x10 square beginning on origin self.polygon1 = Polygon.from_absolute_coordinates([(0, 0), (10, 0), (10, 10), (0, 10)]) self.room1 = Room(self.polygon1, [ Text("1234", Point(3, 3)), Text("Super Cool", Point(4, 7)), Text("Corner Text!", Point(1, 10)) ]) # 10x10 diamond shape centered at origin self.polygon2 = Polygon.from_absolute_coordinates([(10, 0), (0, 10), (-10, 0), (0, -10)]) self.room2 = Room(self.polygon2) # L-shaped room self.polygon3 = Polygon.from_absolute_coordinates([(0, 0), (10, 0), (10, 5), (5, 5), (5, 10), (0, 10)]) self.room3 = Room(self.polygon3)
def test_floor_room_addition(self): self.f.add_room(self.room1) self.assertEqual(self.f.rooms[0], self.room1) p2 = Polygon.from_absolute_coordinates( [(4, 4), (22, 14), (53, 53)] ) r2 = Room(p2) self.f.add_room(r2) self.assertEqual(len(self.f.rooms), 2) self.assertTrue( r2 in self.f.rooms )
def test_show_room(self): '''Test server.show_room(room_id)''' room_name = "lalala" new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() new_room = Room.query.filter(Room.name == room_name).first() result = self.client.get('/api/rooms/{}'.format(int(new_room.room_id))) self.assertIn('"name": "{}",'.format(new_room.name), result.data) self.assertIn('"room_id": {}'.format(new_room.room_id), result.data)
def test_floor_encoding_and_decoding(self): p2 = Polygon.from_absolute_coordinates([(12,0),(22,0),(22,10),(12,10)]) r2 = Room(p2) f1 = Floor("Building cool name","Floor cool name", [self.room1,r2]) f_dump = json.dumps(f1.to_serializable()) f_load = json.loads(f_dump) f2 = Floor.from_serializable(f_load) self.assertEqual(f1,f2)
def test_calculate_scale_amount_and_trasform(self): polygon = Polygon.from_absolute_coordinates( [(0,0),(1024,0),(1024,1024),(2048,1024),(2048,2048),(0,2048)] ) room = Room(polygon) f = Floor("Pippo", "disneyland", [room]) self.assertEqual(f.max_output_size / 2048, f.calculate_scale_amount()) f.normalize() for point in f.rooms[0].polygon.points: self.assertTrue(point.x <= f.max_output_size) self.assertTrue(point.y <= f.max_output_size)
def test_floor_equal(self): p2 = Polygon.from_absolute_coordinates([(12,0),(22,0),(22,10),(12,10)]) r2 = Room(p2) floor = Floor("Building 1", "Floor1", [self.room1,r2]) floor2 = Floor("Building 1", "Floor1",[self.room1,r2]) self.assertEqual(floor,floor2) floor3 = Floor("Building 1", "Floor", [self.room1,r2]) self.assertNotEqual(floor, floor3) floor3 = Floor("Building", "Floor1", [self.room1,r2]) self.assertNotEqual(floor, floor3) floor3 = Floor("Building 1", "Floor1", [self.room1]) self.assertNotEqual(floor, floor3)
def join_room(arg): assert arg.has_key('room'), 'Required argument is missing: "room".' room = Room.get(arg['room']) assert room is not None, 'Specified room is not exists.' assert room.capacity - room.players.count( ) > 0, 'Sorry, specified room is fulled. %s' % (room.capacity - room.players.count()) player = arg['sender'] player.room = room player.put() return _format_message('join_room', 'ok', {'room': str(player.room.key())})
def post(self): data = request.get_json() # pre-validation data = marshal(data, room_resource_fields) if data not in marshal(DB['room'], room_resource_fields) and any( list(data.values())): data = dict(data) data = Room(**data) DB['room'].append(data) return "object is added", 200 return "object is empty or already in DB", 200
def test_associate_text_to_rooms(self): p2 = Polygon.from_absolute_coordinates([(12,0),(22,0),(22,10),(12,10)]) r2 = Room(p2) t1 = Text("Text room 1", Point(5,5)) t2 = Text("Text room 2", Point(15,8)) t3 = Text("Text outside",Point(11,5)) floor = Floor("Building 1", "Floor1",[self.room1, r2]) floor.associate_room_texts([t1,t2,t3]) self.assertEqual( len(self.room1.texts), 1 ) self.assertTrue( len(r2.texts) == 1 ) self.assertTrue( t1 in self.room1.texts ) self.assertTrue( t2 in r2.texts )
def test_room_encoding_and_decoding(self): r = Room([(1, 2), (3, 4), (5, 6)]) self.room1.add_text(Text("Encoded cool text", Point([1, 1]))) s1 = json.dumps(self.room1.to_serializable(), indent=3) d1 = json.loads(s1) r2 = Room.from_serializable(d1) self.assertEqual(self.room1.polygon.points, r2.polygon.points) self.assertEqual(self.room1.texts, r2.texts) s2 = json.dumps(self.room1.to_serializable(), indent=4) d2 = json.loads(s2) self.assertEqual(d1, d2)
def test_create_room_message(self): '''Test POST server.show_room_messages''' room_name = "lalala" room_msg = 'What a happy penguin!' user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user new_user = User(user_name) db.session.add(new_user) db.session.commit() # Add the user to the room new_room = Room.query.filter(Room.name == room_name).first() new_user = User.query.filter(User.name == user_name).first() db.session.add(new_room.join_room(new_user)) db.session.commit() # Have the user say something in the room result = self.client.post( '/api/rooms/{}/messages'.format(int(new_room.room_id)), data={ 'data': room_msg, 'user_id': new_user.user_id }) jason = json.loads(result.data) msg_list = jason["messages"] self.assertIn(new_user.name, result.data) self.assertIn(room_msg, result.data) # We know there should only be one message because everything # gets recreated before and after each test self.assertEqual(len(msg_list), 1)
def test_create_room_message(self): '''Test POST server.show_room_messages''' room_name = "lalala" room_msg = 'What a happy penguin!' user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user new_user = User(user_name) db.session.add(new_user) db.session.commit() # Add the user to the room new_room = Room.query.filter(Room.name == room_name).first() new_user = User.query.filter(User.name == user_name).first() db.session.add(new_room.join_room(new_user)) db.session.commit() # Have the user say something in the room result = self.client.post('/api/rooms/{}/messages'.format( int(new_room.room_id)), data={ 'data': room_msg, 'user_id': new_user.user_id }) jason = json.loads(result.data) msg_list = jason["messages"] self.assertIn(new_user.name, result.data) self.assertIn(room_msg, result.data) # We know there should only be one message because everything # gets recreated before and after each test self.assertEqual(len(msg_list), 1)
def load_Room(): """Load room numbers from room.csv into database.""" print "rooms" Room.query.delete() for row in open("seed_data/room"): row = row.strip() items = row.split(",") room = Room(room_loc=items[0], capacity=items[1]) db.session.add(room) db.session.commit()
def setUp(self): # 10x10 square beginning on origin self.polygon1 = Polygon.from_absolute_coordinates([(0,0),(10,0),(10,10),(0,10)]) self.room1 = Room(self.polygon1, [ Text("1234",Point(3,3)), Text("Super Cool",Point(4,7)), Text("Corner Text!",Point(1,10)) ]) # 10x10 diamond shape centered at origin self.polygon2 = Polygon.from_absolute_coordinates([(10,0), (0, 10), (-10, 0), (0, -10)]) self.room2 = Room(self.polygon2) # L-shaped room self.polygon3 = Polygon.from_absolute_coordinates([(0,0),(10,0),(10,5),(5,5),(5,10),(0,10)]) self.room3 = Room(self.polygon3)
def video_sync_api(room_name): room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) update_current_time(room) return json_response({"current_time":room.current_time})
class RoomTest(unittest.TestCase): def setUp(self): # 10x10 square beginning on origin self.polygon1 = Polygon.from_absolute_coordinates([(0,0),(10,0),(10,10),(0,10)]) self.room1 = Room(self.polygon1, [ Text("1234",Point(3,3)), Text("Super Cool",Point(4,7)), Text("Corner Text!",Point(1,10)) ]) # 10x10 diamond shape centered at origin self.polygon2 = Polygon.from_absolute_coordinates([(10,0), (0, 10), (-10, 0), (0, -10)]) self.room2 = Room(self.polygon2) # L-shaped room self.polygon3 = Polygon.from_absolute_coordinates([(0,0),(10,0),(10,5),(5,5),(5,10),(0,10)]) self.room3 = Room(self.polygon3) def test_room_equality(self): # Equality is true r2 = Room(self.polygon1.clone(), [ t.clone() for t in self.room1.texts ]) r3 = Room( self.polygon1.clone(), [ t.clone() for t in self.room1.texts[1:] ] ) # Equality is false d = Room( self.polygon1.clone().traslate(1, 0), [ t.clone() for t in self.room1.texts ] ) self.assertEqual(self.room1, r2) self.assertEqual(self.room1, r3) self.assertNotEqual(self.room1, d) def test_room_cloning(self): r2 = self.room1.clone() self.assertEqual(r2.texts, self.room1.texts) self.assertEqual(r2.polygon, self.room1.polygon) self.assertEqual(r2, self.room1) self.assertTrue(r2 is not self.room1) def test_room_min_absolute_point(self): def check_min_abs_point(room, expected_x, expected_y): minX, minY = room.min_absolute_point() self.assertEqual(minX, expected_x) self.assertEqual(minY, expected_y) check_min_abs_point(self.room1, 0, 0) self.room1.traslate(5, 5) check_min_abs_point(self.room1, 5, 5) self.room1.reflect_y() check_min_abs_point(self.room1, 5, -15) def test_room_max_absolute_point(self): def check_max_abs_point(room, expected_x, expected_y): maxX, maxY = room.max_absolute_point() self.assertEqual(maxX, expected_x) self.assertEqual(maxY, expected_y) check_max_abs_point(self.room1, 10, 10) self.room1.traslate(5, 5) check_max_abs_point(self.room1, 15, 15) self.room1.reflect_y() check_max_abs_point(self.room1, 15, -5) def test_room_contains_text(self): t1 = Text("In text!",Point(5,5)) t2 = Text("Out text!",Point(11,5)) self.assertTrue(self.room1.contains_text(t1)) self.assertFalse(self.room1.contains_text(t2)) ################### # TRANSFORMATIONS # ################### def test_room_traslation(self): def check_room_traslation(room, amount_x, amount_y): room.polygon = MagicMock(); old_texts = [ t.clone() for t in room.texts ] room.traslate(amount_x, amount_y) # Check polygon have been traslated room.polygon.traslate_ac.assert_called_with(amount_x, amount_y) # Pending: test for every Text on room for new_text, old_text in zip(room.texts, old_texts): self.assertTrue(new_text.anchor_point.x == old_text.anchor_point.x + amount_x) self.assertTrue(new_text.anchor_point.y == old_text.anchor_point.y + amount_y) check_room_traslation(self.room1, 20, 33) check_room_traslation(self.room1, -10, -23) check_room_traslation(self.room1, 20, -33) check_room_traslation(self.room1, -10, 23) check_room_traslation(self.room1, 0, 0) def test_room_reflection(self): self.room1.reflect_y() self.assertEqual( self.room1.polygon.points, [Point(0,0), Point(10,0), Point(10,-10), Point(0,-10)] ) self.polygon1.anchor_point.reflect_y = MagicMock() self.polygon1.reflect_y = MagicMock() for t in self.room1.texts: t.anchor_point.reflect_y = MagicMock() self.room1.reflect_y() self.polygon1.anchor_point.reflect_y.assert_called_once_with() self.polygon1.reflect_y.assert_called_once_with() for t in self.room1.texts: t.anchor_point.reflect_y.assert_called_once_with() def test_room_scale(self): self.room1.polygon = MagicMock() for p in self.room1.texts: p.anchor_point.scale = MagicMock() self.room1.scale(2) for t in self.room1.texts: t.anchor_point.scale.assert_called_with(2) self.room1.polygon.scale.assert_called_with(2)
def test_show_room_message(self): '''Test GET server.show_room_messages for all four path options. /api/rooms/<int:room_id>/messages /api/rooms/<int:room_id>/messages?last_updated=<datetime:last_updated> /api/rooms/<int:room_id>/messages?limit_responses=<int:limit_responses> /api/rooms/<int:room_id>/messages?last_updated=<datetime:last_updated>&limit_responses=<int:limit_responses> ''' # Background Context: # Flask's app.test_client normally resets the session scope # upon every call to the test_client. Model objects are bound to the # session. Because each call to the test_client ends the scope of a # session, all the Model objects become detached and difficult to work # with. # To solve this, we explicitly set the scope as shared so we can issue # multiple calls to test_client without having to re-bind our objects # to each new session. That's the whole purpose of this next line. # Note: There's still something strange going on with session scoping with self.client as test_client: # if True: room_name = "lalala" room_msg1 = 'What a happy penguin am I!' room_msg2 = "It's practically impossible to look at a penguin and feel angry." room_msg3 = 'Burn everything' user_name = 'Penny Penguin' # Create a room new_room = Room(name=room_name) db.session.add(new_room) db.session.commit() # Create a user penny_penguin = User(user_name) db.session.add(penny_penguin) db.session.commit() # Add the user to the room # new_room = Room.query.filter(Room.name == room_name).first() # penny_penguin = User.query.filter(User.name == user_name).first() balloonicorn = User.query.get(1) anonymouse = User.query.get(2) # print type(balloonicorn), balloonicorn, balloonicorn.user_id # print type(anonymouse), anonymouse, anonymouse.user_id # db.session.add(main_room.join_room(anonymouse)) db.session.add(new_room.join_room(penny_penguin)) db.session.add(new_room.join_room(balloonicorn)) db.session.add(new_room.join_room(anonymouse)) db.session.commit() # import pdb; pdb.set_trace() # print type(balloonicorn), balloonicorn, balloonicorn.user_id # print type(anonymouse), anonymouse, anonymouse.user_id # Have the user say something in the room #result = self.client.get('/api/rooms/{}'.format(int(new_room.room_id))) # import pdb; pdb.set_trace() result_post_1 = test_client.post( # result_post_1 = self.client.post( '/api/rooms/{}/messages'.format(int(new_room.room_id)), data={ 'data': room_msg1, 'user_id': anonymouse.user_id }) # print "\n\n\nYO\n" # import pdb; pdb.set_trace() balloonicorn.name # balloonicorn = db.session.merge(balloonicorn) # print "\n\n\n" # print "Result POST 1: \n", result_post_1.data # penny_penguin = db.session.merge(penny_penguin) # anonymouse = db.session.merge(anonymouse) # balloonicorn = db.session.merge(balloonicorn) # new_room = db.session.merge(new_room) # FIXME: Make this a proper datestamp # time_stamp = datetime.now().strftime() result_post_2 = test_client.post( # result_post_2 = self.client.post( '/api/rooms/{}/messages'.format(int(new_room.room_id)), data={ 'data': room_msg2, 'user_id': penny_penguin.user_id }) # import pdb; pdb.set_trace() # print "Result POST 2: \n", result_post_2.data # penny_penguin = db.session.merge(penny_penguin) # anonymouse = db.session.merge(anonymouse) # balloonicorn = db.session.merge(balloonicorn) # new_room = db.session.merge(new_room) result_post_3 = test_client.post( '/api/rooms/{}/messages'.format(int(new_room.room_id)), data={ 'data': room_msg3, 'user_id': balloonicorn.user_id }) # print "Result POST 3: \n", result_post_3.data # penny_penguin = db.session.merge(penny_penguin) # anonymouse = db.session.merge(anonymouse) # balloonicorn = db.session.merge(balloonicorn) # new_room = db.session.merge(new_room) # import pdb; pdb.set_trace() result_get_3 = test_client.get( '/api/rooms/{}/messages'.format(int(new_room.room_id))) # print "Result GET 3: \n", result_get_3.data # time_stamp = datetime.timestamp() #FIXME: get this into unix time? # result4 = self.client.get( # '/api/rooms/{}/messages?last_updated={}'.format(int(new_room.room_id),time_stamp)) # print "Result 4: \n", result4.data # penny_penguin = db.session.merge(penny_penguin) # anonymouse = db.session.merge(anonymouse) # balloonicorn = db.session.merge(balloonicorn) # new_room = db.session.merge(new_room) jason = json.loads(result_get_3.data) msg_list = jason["messages"] self.assertIn(penny_penguin.name, result_get_3.data) self.assertIn(room_msg1, result_get_3.data) self.assertIn(room_msg2, result_get_3.data) self.assertEqual(len(msg_list), 3)
def room_api(room_name=None): user = users.get_current_user() if flask.request.method == 'GET': if room_name is None: rooms = [] if not user: rooms = Room.fetch_all_anonymous() else: rooms = Room.fetch_all() for room in rooms: update_current_time(room) return json_response([room.to_dict() for room in rooms]) else: room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) update_current_time(room) return json_response(room.to_dict()) elif flask.request.method == 'POST': if not user: return json_fail(Reason.LOGIN_REQUIRED) else: room_info = flask.request.get_json(silent=True) if room_info is None: return json_fail(Reason.INVALID_PARAMETER) if "name" not in room_info: return json_fail(Reason.ROOM_NAME_REQUIRED) room = Room.fetch_by_name(room_info["name"]) logging.info('create_room(%s):%s'%(room_info["name"],room.__class__.__name__)) if room is not None: return json_fail(Reason.EXIST_ROOM_NAME) room = Room(creator_email=user.email(), name=room_info["name"]) if "current_time" in room_info: room.current_time=int(room_info["current_time"]) if "cover" in room_info: room.cover=room_info["cover"] room.put() update_current_time(room) return json_succ(data=room.to_dict()) elif flask.request.method == 'PUT': if not user: return json_fail(Reason.LOGIN_REQUIRED) room = Room.fetch_by_name(room_name) logging.info('update_room(%s):%s'%(room_name,room.__class__.__name__)) if room is None: return json_fail(Reason.NO_ROOM_FOUND) if user.email() != room.creator_email: return json_fail(Reason.FORBIDDEN_OPERATION) room_info = flask.request.get_json(silent=True) if room_info is None: return json_fail(Reason.INVALID_PARAMETER) if "current_time" in room_info: room.current_time=int(room_info["current_time"]) if "cover" in room_info: room.cover=room_info["cover"] room.put() return json_succ() elif flask.request.method == 'DELETE': if not user: return json_fail(Reason.LOGIN_REQUIRED) room = Room.fetch_by_name(room_name) logging.info('delete_room(%s):%s'%(room_name,room.__class__.__name__)) if room is not None: if user.email() != room.creator_email: return json_fail(Reason.FORBIDDEN_OPERATION) else: room.key.delete() return json_succ() else: return json_fail(Reason.NO_ROOM_FOUND, room_name) else: return json_fail(Reason.INVALID_PARAMETER)
def video_api(room_name, video_index=None): user = users.get_current_user() if flask.request.method == 'GET': room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) if video_index is None: return json_response(room.video_ids) elif video_index >= len(room.video_ids): return json_fail(Reason.INVALID_PARAMETER) else: return json_response(room.video_ids[video_index]) elif flask.request.method == 'POST': if not user: return json_fail(Reason.LOGIN_REQUIRED) room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) if user.email() != room.creator_email: return json_fail(Reason.FORBIDDEN_OPERATION) video_info = flask.request.get_json(silent=True) if video_info is None or "id" not in video_info: return json_fail(Reason.INVALID_PARAMETER) room.video_ids.append(video_info["id"]); room.put() return json_succ() elif flask.request.method == 'PUT': if not user: return json_fail(Reason.LOGIN_REQUIRED) room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) if user.email() != room.creator_email: return json_fail(Reason.FORBIDDEN_OPERATION) video_action = flask.request.get_json(silent=True) if video_action is None: return json_fail(Reason.INVALID_PARAMETER) if "op" not in video_action or "current_time" not in video_action or "roundtrip" not in video_action: return json_fail(Reason.INVALID_PARAMETER) if video_action["op"] not in ['NOTSTARTED', 'PAUSED', 'PLAYING', 'ENDED']: return json_fail(Reason.INVALID_PARAMETER) room.state = video_action["op"] # Save current_time+roundtrip/2 and last updated time. # When read, it'll be now()-last_updated_time+current_time+roundtrip/2 room.current_time = int(int(video_action["current_time"]) + float(video_action["roundtrip"])/2) room.put() return json_succ() elif flask.request.method == 'DELETE': if not user: return json_fail(Reason.LOGIN_REQUIRED) room = Room.fetch_by_name(room_name) if room is None: return json_fail(Reason.NO_ROOM_FOUND) if user.email() != room.creator_email: return json_fail(Reason.FORBIDDEN_OPERATION) #could only remove video_id at 0 video_index = int(video_index) if video_index != 0: return json_fail(Reason.INVALID_PARAMETER) logging.info('delete_video(%s:%d):%s'%(room_name,video_index,room.__class__.__name__)) room.video_ids = room.video_ids[1:] room.put() return json_succ() else: return json_fail(Reason.INVALID_PARAMETER)
def setUp(self): self.polygon1 = Polygon.from_absolute_coordinates([(1, 2), (3, 4), (5, 6)]) self.room1 = Room(self.polygon1)
class JsonEncodingTest(unittest.TestCase): def setUp(self): self.polygon1 = Polygon.from_absolute_coordinates([(1, 2), (3, 4), (5, 6)]) self.room1 = Room(self.polygon1) def test_room_to_serializable(self): self.polygon1.to_serializable = MagicMock(return_value="pippo_serializzato") self.room1.add_text(Text("Encoded cool text", Point([1, 1]))) self.assertEqual( self.room1.to_serializable(), {"polygon": "pippo_serializzato", "texts": serialize_list(self.room1.texts)} ) def test_room_text_serializable(self): t1 = Text("Encoded cool text", Point([1, 1])) self.assertEqual(t1.to_serializable(), {"text": t1.text, "anchor_point": t1.anchor_point.to_serializable()}) t2 = Text.from_serializable(t1.to_serializable()) self.assertEqual(t1, t2) def test_point_serializable(self): p = Point([1, 2]) self.assertEqual(p.to_serializable(), {"x": p.x, "y": p.y}) p2 = Point.from_serializable(p.to_serializable()) self.assertEqual(p, p2) def test_room_encoding_and_decoding(self): r = Room([(1, 2), (3, 4), (5, 6)]) self.room1.add_text(Text("Encoded cool text", Point([1, 1]))) s1 = json.dumps(self.room1.to_serializable(), indent=3) d1 = json.loads(s1) r2 = Room.from_serializable(d1) self.assertEqual(self.room1.polygon.points, r2.polygon.points) self.assertEqual(self.room1.texts, r2.texts) s2 = json.dumps(self.room1.to_serializable(), indent=4) d2 = json.loads(s2) self.assertEqual(d1, d2) def test_floor_to_serializable(self): p2 = Polygon.from_absolute_coordinates([(12, 0), (22, 0), (22, 10), (12, 10)]) r2 = Room(p2) f = Floor("Building cool name", "Floor cool name", [self.room1, r2]) self.assertEqual( f.to_serializable(), { "walls": [], "windows": [], "b_id": f.b_id, "f_id": f.f_id, "rooms": [self.room1.to_serializable(), r2.to_serializable()], }, ) def test_floor_encoding_and_decoding(self): p2 = Polygon.from_absolute_coordinates([(12, 0), (22, 0), (22, 10), (12, 10)]) r2 = Room(p2) f1 = Floor("Building cool name", "Floor cool name", [self.room1, r2]) f_dump = json.dumps(f1.to_serializable()) f_load = json.loads(f_dump) f2 = Floor.from_serializable(f_load) self.assertEqual(f1, f2) def test_polygon_to_serializable(self): self.polygon1.anchor_point.to_serializable = MagicMock(return_value="anchor_pippo") for p in self.polygon1.points: p.to_serializable = MagicMock(return_value="pippo_point") self.assertEqual( self.polygon1.to_serializable(), {"anchor_point": "anchor_pippo", "points": ["pippo_point" for p in self.polygon1.points]}, ) def test_polygon_from_serializable(self): p_dump = json.dumps(self.polygon1.to_serializable()) p_load = json.loads(p_dump) pol2 = Polygon.from_serializable(p_load) self.assertEqual(self.polygon1, pol2)