id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
146,848
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/queen.py
chess_py.pieces.queen.Queen
class Queen(Bishop, Piece): def __init__(self, input_color, location): Piece.__init__(self, input_color, location) def _symbols(self): return {color.white: "♛", color.black: "♕"} def __str__(self): return "Q" def possible_moves(self, position): for move in itertools.chain(Rook.possible_moves(self, position), Bishop.possible_moves(self, position)): yield move
class Queen(Bishop, Piece): def __init__(self, input_color, location): pass def _symbols(self): pass def __str__(self): pass def possible_moves(self, position): pass
5
0
3
0
3
0
1
0
2
1
0
0
4
0
4
26
14
3
11
6
6
0
10
6
5
2
3
1
5
146,849
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/piece_const.py
chess_py.pieces.piece_const.PieceValues
class PieceValues: def __init__(self): self.PAWN_VALUE = 1 self.KNIGHT_VALUE = 3 self.BISHOP_VALUE = 3.5 self.ROOK_VALUE = 5 self.QUEEN_VALUE = 9 self.KING_VALUE = 999 @classmethod def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value): """ Manual init method for external piece values :type: PAWN_VALUE: int :type: KNIGHT_VALUE: int :type: BISHOP_VALUE: int :type: ROOK_VALUE: int :type: QUEEN_VALUE: int """ piece_values = cls() piece_values.PAWN_VALUE = pawn_value piece_values.KNIGHT_VALUE = knight_value piece_values.BISHOP_VALUE = bishop_value piece_values.ROOK_VALUE = rook_value piece_values.QUEEN_VALUE = queen_value piece_values.KING_VALUE = king_value return piece_values def val(self, piece, ref_color): """ Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int """ if piece is None: return 0 if ref_color == piece.color: const = 1 else: const = -1 if isinstance(piece, Pawn): return self.PAWN_VALUE * const elif isinstance(piece, Queen): return self.QUEEN_VALUE * const elif isinstance(piece, Bishop): return self.BISHOP_VALUE * const elif isinstance(piece, Rook): return self.ROOK_VALUE * const elif isinstance(piece, Knight): return self.KNIGHT_VALUE * const elif isinstance(piece, King): return self.KING_VALUE * const return 0
class PieceValues: def __init__(self): pass @classmethod def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value): ''' Manual init method for external piece values :type: PAWN_VALUE: int :type: KNIGHT_VALUE: int :type: BISHOP_VALUE: int :type: ROOK_VALUE: int :type: QUEEN_VALUE: int ''' pass def val(self, piece, ref_color): ''' Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int ''' pass
5
2
18
1
12
5
4
0.37
0
6
6
0
2
6
3
3
58
6
38
13
33
14
31
12
27
9
0
1
11
146,850
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/pawn.py
chess_py.pieces.pawn.Pawn
class Pawn(Piece): def __init__(self, input_color, location): """ Initializes a Pawn that is capable of moving :type: input_color: Color :type: location: Location """ self.just_moved_two_steps = False super(Pawn, self).__init__(input_color, location) def _symbols(self): return {color.white: "♟", color.black: "♙"} def __str__(self): return "P" def on_home_row(self, location=None): """ Finds out if the piece is on the home row. :return: bool for whether piece is on home row or not """ location = location or self.location return (self.color == color.white and location.rank == 1) or \ (self.color == color.black and location.rank == 6) def would_move_be_promotion(self, location=None): """ Finds if move from current get_location would result in promotion :type: location: Location :rtype: bool """ location = location or self.location return (location.rank == 1 and self.color == color.black) or \ (location.rank == 6 and self.color == color.white) def square_in_front(self, location=None): """ Finds square directly in front of Pawn :type: location: Location :rtype: Location """ location = location or self.location return location.shift_up() if self.color == color.white else location.shift_down() def two_squares_in_front(self, location): """ Finds square two squares in front of Pawn :type: location: Location :rtype: get_location """ return self.square_in_front(self.square_in_front(location)) def create_promotion_moves(self, status, location=None): location = location or self.square_in_front() def create_each_move(piece): return Move(end_loc=location, piece=self, status=status, start_loc=self.location, promoted_to_piece=piece) yield create_each_move(Queen) yield create_each_move(Rook) yield create_each_move(Bishop) yield create_each_move(Knight) def forward_moves(self, position): """ Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list """ if position.is_square_empty(self.square_in_front(self.location)): """ If square in front is empty add the move """ if self.would_move_be_promotion(): for move in self.create_promotion_moves(notation_const.PROMOTE): yield move else: yield self.create_move(end_loc=self.square_in_front(self.location), status=notation_const.MOVEMENT) if self.on_home_row() and \ position.is_square_empty(self.two_squares_in_front(self.location)): """ If pawn is on home row and two squares in front of the pawn is empty add the move """ yield self.create_move( end_loc=self.square_in_front(self.square_in_front(self.location)), status=notation_const.MOVEMENT ) def _one_diagonal_capture_square(self, capture_square, position): """ Adds specified diagonal as a capture move if it is one """ if self.contains_opposite_color_piece(capture_square, position): if self.would_move_be_promotion(): for move in self.create_promotion_moves(status=notation_const.CAPTURE_AND_PROMOTE, location=capture_square): yield move else: yield self.create_move(end_loc=capture_square, status=notation_const.CAPTURE) def capture_moves(self, position): """ Finds out all possible capture moves :rtype: list """ try: right_diagonal = self.square_in_front(self.location.shift_right()) for move in self._one_diagonal_capture_square(right_diagonal, position): yield move except IndexError: pass try: left_diagonal = self.square_in_front(self.location.shift_left()) for move in self._one_diagonal_capture_square(left_diagonal, position): yield move except IndexError: pass def on_en_passant_valid_location(self): """ Finds out if pawn is on enemy center rank. :rtype: bool """ return (self.color == color.white and self.location.rank == 4) or \ (self.color == color.black and self.location.rank == 3) def _is_en_passant_valid(self, opponent_pawn_location, position): """ Finds if their opponent's pawn is next to this pawn :rtype: bool """ try: pawn = position.piece_at_square(opponent_pawn_location) return pawn is not None and \ isinstance(pawn, Pawn) and \ pawn.color != self.color and \ position.piece_at_square(opponent_pawn_location).just_moved_two_steps except IndexError: return False def add_one_en_passant_move(self, direction, position): """ Yields en_passant moves in given direction if it is legal. :type: direction: function :type: position: Board :rtype: gen """ try: if self._is_en_passant_valid(direction(self.location), position): yield self.create_move( end_loc=self.square_in_front(direction(self.location)), status=notation_const.EN_PASSANT ) except IndexError: pass def en_passant_moves(self, position): """ Finds possible en passant moves. :rtype: list """ # if pawn is not on a valid en passant get_location then return None if self.on_en_passant_valid_location(): for move in itertools.chain(self.add_one_en_passant_move(lambda x: x.shift_right(), position), self.add_one_en_passant_move(lambda x: x.shift_left(), position)): yield move def possible_moves(self, position): """ Finds out the locations of possible moves given board.Board position. :pre get_location is on board and piece at specified get_location on position :type: position: Board :rtype: list """ for move in itertools.chain(self.forward_moves(position), self.capture_moves(position), self.en_passant_moves(position)): yield move
class Pawn(Piece): def __init__(self, input_color, location): ''' Initializes a Pawn that is capable of moving :type: input_color: Color :type: location: Location ''' pass def _symbols(self): pass def __str__(self): pass def on_home_row(self, location=None): ''' Finds out if the piece is on the home row. :return: bool for whether piece is on home row or not ''' pass def would_move_be_promotion(self, location=None): ''' Finds if move from current get_location would result in promotion :type: location: Location :rtype: bool ''' pass def square_in_front(self, location=None): ''' Finds square directly in front of Pawn :type: location: Location :rtype: Location ''' pass def two_squares_in_front(self, location): ''' Finds square two squares in front of Pawn :type: location: Location :rtype: get_location ''' pass def create_promotion_moves(self, status, location=None): pass def create_each_move(piece): pass def forward_moves(self, position): ''' Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list ''' pass def _one_diagonal_capture_square(self, capture_square, position): ''' Adds specified diagonal as a capture move if it is one ''' pass def capture_moves(self, position): ''' Finds out all possible capture moves :rtype: list ''' pass def on_en_passant_valid_location(self): ''' Finds out if pawn is on enemy center rank. :rtype: bool ''' pass def _is_en_passant_valid(self, opponent_pawn_location, position): ''' Finds if their opponent's pawn is next to this pawn :rtype: bool ''' pass def add_one_en_passant_move(self, direction, position): ''' Yields en_passant moves in given direction if it is legal. :type: direction: function :type: position: Board :rtype: gen ''' pass def en_passant_moves(self, position): ''' Finds possible en passant moves. :rtype: list ''' pass def possible_moves(self, position): ''' Finds out the locations of possible moves given board.Board position. :pre get_location is on board and piece at specified get_location on position :type: position: Board :rtype: list ''' pass
18
13
11
1
6
4
2
0.69
1
8
5
0
16
2
16
29
202
33
100
28
82
69
75
27
57
5
1
3
35
146,851
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/knight.py
chess_py.pieces.knight.Knight
class Knight(Piece): def __init__(self, input_color, location): """ Initializes Knight :type: input_color: Color :type: location Location """ super(Knight, self).__init__(input_color, location) def _symbols(self): return {color.white: "♞", color.black: "♘"} def __str__(self): return "N" @staticmethod def _rotate_direction_ninety_degrees(direction): if direction == 3: return 0, 2 right_angles = [direction - 1, direction + 1] for index, angle in enumerate(right_angles): if angle == -1: right_angles[index] = 3 elif angle == 4: right_angles[index] = 0 return right_angles def possible_moves(self, position): """ Finds all possible knight moves :type: position Board :rtype: list """ for direction in [0, 1, 2, 3]: angles = self._rotate_direction_ninety_degrees(direction) for angle in angles: try: end_loc = self.location.shift(angle).shift(direction).shift(direction) if position.is_square_empty(end_loc): status = notation_const.MOVEMENT elif not position.piece_at_square(end_loc).color == self.color: status = notation_const.CAPTURE else: continue yield Move(end_loc=end_loc, piece=self, status=status, start_loc=self.location) except IndexError: pass
class Knight(Piece): def __init__(self, input_color, location): ''' Initializes Knight :type: input_color: Color :type: location Location ''' pass def _symbols(self): pass def __str__(self): pass @staticmethod def _rotate_direction_ninety_degrees(direction): pass def possible_moves(self, position): ''' Finds all possible knight moves :type: position Board :rtype: list ''' pass
7
2
9
1
7
2
3
0.28
1
4
1
0
4
0
5
18
53
7
36
14
29
10
29
13
23
6
1
4
14
146,852
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/game/interface.py
chess_py.game.interface.UCI
class UCI: def __init__(self, player, engine_name, author): """ :type: player: Player """ self.player = player self.engine = engine_name self.author = author self.position = Board.init_default() self.running = True self.latest_input = "" def play(self): self.runInParallel(lambda: self.read(), lambda: self.set_up()) self.set_up() def set_up(self): self.wait_for("uci") self.write("id name " + self.engine) self.write("id author " + self.author) self.write("uciok") self.wait_for("ucinewgame") self.start_game() def start_game(self): if self.latest_input == "isready": self.write("readyok") self.wait_for("") def wait_for(self, command): """ Waits until ``self.latest_input`` is a certain command :type command: """ while self.latest_input != command: pass def read(self): """ Continuously reads from the console and updates ``self.latest_input`` with latest command. Runs as a side process at all times so main process has the most current information form the console accessed through ``self.latest_input``. """ while self.running: self.latest_input = self.player.getUCI() def write(self, command): """ Writes to the console given the command. Called by the main process when it needs to send commands to the console. :type: command: str """ self.player.setUCI(command) def runInParallel(*fns): """ Runs multiple processes in parallel. :type: fns: def """ proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join()
class UCI: def __init__(self, player, engine_name, author): ''' :type: player: Player ''' pass def play(self): pass def set_up(self): pass def start_game(self): pass def wait_for(self, command): ''' Waits until ``self.latest_input`` is a certain command :type command: ''' pass def read(self): ''' Continuously reads from the console and updates ``self.latest_input`` with latest command. Runs as a side process at all times so main process has the most current information form the console accessed through ``self.latest_input``. ''' pass def write(self, command): ''' Writes to the console given the command. Called by the main process when it needs to send commands to the console. :type: command: str ''' pass def runInParallel(*fns): ''' Runs multiple processes in parallel. :type: fns: def ''' pass
9
5
9
1
5
3
2
0.63
0
0
0
0
8
6
8
8
76
14
38
18
29
24
38
18
29
3
0
1
13
146,853
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_core/test_board.py
tests.test_core.test_board.TestBoard
class TestBoard(TestCase): def setUp(self): self.board = Board.init_default() def test_init_default(self): white = color.white black = color.black test = Board([ # First rank [Rook(white, Location(0, 0)), Knight(white, Location(0, 1)), Bishop(white, Location(0, 2)), Queen(white, Location(0, 3)), King(white, Location(0, 4)), Bishop(white, Location(0, 5)), Knight(white, Location(0, 6)), Rook(white, Location(0, 7))], # Second rank [Pawn(white, Location(1, file)) for file in range(8)], # Third rank [None for _ in range(8)], # Fourth rank [None for _ in range(8)], # Fifth rank [None for _ in range(8)], # Sixth rank [None for _ in range(8)], # Seventh rank [Pawn(black, Location(6, file)) for file in range(8)], # Eighth rank [Rook(black, Location(7, 0)), Knight(black, Location(7, 1)), Bishop(black, Location(7, 2)), Queen(black, Location(7, 3)), King(black, Location(7, 4)), Bishop(black, Location(7, 5)), Knight(black, Location(7, 6)), Rook(black, Location(7, 7))]]) self.assertEqual(self.board, test) def test_copy(self): tester = Board.init_default() for num, row in enumerate(self.board.position): for index, piece in enumerate(row): self.assertEqual(piece, tester.position[num][index]) def test_piece_at_square(self): self.assertEqual(self.board.piece_at_square(Location(0, 0)), Rook(color.white, Location(0, 0))) self.assertEqual(self.board.piece_at_square(Location(1, 0)), Pawn(color.white, Location(1, 0))) self.assertEqual(self.board.piece_at_square(Location(0, 1)), Knight(color.white, Location(0, 1))) def test_is_square_empty(self): self.assertTrue(self.board.is_square_empty(Location(2, 0))) self.assertFalse(self.board.is_square_empty(Location(0, 3))) def test_material_advantage_parity(self): self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), 0) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), 0) def test_material_advantage_black_advantage(self): self.board.position[0][0] = None self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), -5) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), 5) self.board = Board.init_default() self.board.position[0][1] = None self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), -3) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), 3) def test_material_advantage_white_advantage(self): self.board = Board.init_default() self.board.position[7][0] = None self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), 5) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), -5) self.board = Board.init_default() self.board.position[7][3] = None self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), 9) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), -9) self.board = Board.init_default() self.board.position[7][2] = None self.assertEqual(self.board.material_advantage(color.white, piece_const.PieceValues()), 3.5) self.assertEqual(self.board.material_advantage(color.black, piece_const.PieceValues()), -3.5) def test_advantage_as_result(self): self.assertEqual(self.board.advantage_as_result(converter.long_alg("e2e4", self.board), piece_const.PieceValues()), 0) self.board.position[1][3] = None self.assertEqual( self.board.advantage_as_result(converter.long_alg("d1d7", self.board), piece_const.PieceValues()), 0) self.board.update(converter.short_alg("e3", color.white, self.board)) self.assertEqual( self.board.advantage_as_result( converter.short_alg("Bd2", color.white, self.board), piece_const.PieceValues()), -1) def test_all_possible_moves_1(self): """ Print statement to easily get the list of moves in string form. Used for constructing tests. for move in self.board.all_possible_moves(color.white): print("\""+ str(move) + "\", ", end="") """ moves = {"b1c3", "b1a3", "g1h3", "g1f3", "a2a3", "a2a4", "b2b3", "b2b4", "c2c3", "c2c4", "d2d3", "d2d4", "e2e3", "e2e4", "f2f3", "f2f4", "g2g3", "g2g4", "h2h3", "h2h4"} self.assertEqual(moves, {str(move) for move in self.board.all_possible_moves(color.white)}) def test_all_possible_moves_2(self): self.board.update(converter.long_alg("e2e4", self.board)) moves = {"a7a6", "a7a5", "b7b6", "b7b5", "c7c6", "c7c5", "d7d6", "d7d5", "e7e6", "e7e5", "f7f6", "f7f5", "g7g6", "g7g5", "h7h6", "h7h5", "b8a6", "b8c6", "g8f6", "g8h6"} self.assertEqual(moves, {str(move) for move in self.board.all_possible_moves(color.black)}) def test_no_moves(self): self.assertFalse(self.board.no_moves(color.white)) self.assertFalse(self.board.no_moves(color.black)) # Scholar's Mate self.board.update(converter.short_alg("f4", color.white, self.board)) self.board.update(converter.short_alg("e5", color.black, self.board)) self.board.update(converter.short_alg("g4", color.white, self.board)) self.board.update(converter.short_alg("Qh4", color.black, self.board)) self.assertTrue(self.board.no_moves(color.white)) def test_find_piece(self): self.assertEqual(self.board.find_piece(Rook(color.white, Location(0, 0))), Location(0, 0)) self.assertEqual(self.board.find_piece(Rook(color.black, Location(7, 0))), Location(7, 0)) self.assertNotEqual(self.board.find_piece(Rook(color.black, Location(7, 0))), Location(3, 0)) self.assertEqual(self.board.find_piece(Pawn(color.white, Location(0, 0))), Location.from_string("a2")) self.assertEqual(self.board.find_piece(Knight(color.white, Location(0, 0))), Location.from_string("b1")) def test_find_king(self): self.assertEqual(self.board.find_king(color.white), Location(0, 4)) self.assertEqual(self.board.find_king(color.black), Location(7, 4)) def test_get_king(self): self.assertEqual(self.board.get_king(color.white), King(color.white, Location(0, 4))) self.assertEqual(self.board.get_king(color.black), King(color.black, Location(7, 4))) def test_remove_piece_at_square(self): test_board = Board.init_default() test_board.position[0][0] = None self.board.remove_piece_at_square(Location(0, 0)) self.assertEqual(self.board, test_board) def test_place_piece_at_square(self): test = Board.init_default() pawn = Pawn(color.white, Location.from_string("e3")) test.position[2][4] = pawn self.board.place_piece_at_square(pawn, Location.from_string("e3")) self.assertEqual(self.board, test) def test_move_piece(self): test = Board.init_default() pawn = test.position[1][4] test.position[1][4] = None test.position[3][4] = pawn self.board.move_piece(Location.from_string("e2"), Location.from_string("e4")) self.assertEqual(self.board, test) def test_update_pawn_moves_one_step(self): pawn = self.board.piece_at_square(Location.from_string("e2")) self.board.update(converter.long_alg("e2e3", self.board)) self.assertIsInstance(pawn, Pawn) self.assertEqual(self.board.piece_at_square(Location.from_string("e3")), pawn) self.assertIsNone(self.board.piece_at_square(Location.from_string("e2"))) self.assertFalse(pawn.just_moved_two_steps) def test_update_pawn_moves_two_steps(self): pawn = self.board.piece_at_square(Location.from_string("e2")) self.board.update(converter.long_alg("e2e4", self.board)) self.assertIsInstance(pawn, Pawn) self.assertEqual(self.board.piece_at_square(Location.from_string("e4")), pawn) self.assertIsNone(self.board.piece_at_square(Location.from_string("e2"))) self.assertIsNone(self.board.piece_at_square(Location.from_string("e3"))) self.assertTrue(pawn.just_moved_two_steps) self.board.update(converter.long_alg("d2d4", self.board)) self.assertFalse(pawn.just_moved_two_steps) def test_update_moves_king_side_castle(self): self.board.update(converter.short_alg("e4", color.white, self.board)) self.board.update(converter.short_alg("Nf3", color.white, self.board)) self.board.update(converter.short_alg("Be2", color.white, self.board)) self.board.update(converter.short_alg("o-o", color.white, self.board)) king = self.board.piece_at_square(Location.from_string("g1")) self.assertIsInstance(king, King) self.assertTrue(king.has_moved) rook = self.board.piece_at_square(Location.from_string("f1")) self.assertIsInstance(rook, Rook) self.assertTrue(rook.has_moved)
class TestBoard(TestCase): def setUp(self): pass def test_init_default(self): pass def test_copy(self): pass def test_piece_at_square(self): pass def test_is_square_empty(self): pass def test_material_advantage_parity(self): pass def test_material_advantage_black_advantage(self): pass def test_material_advantage_white_advantage(self): pass def test_advantage_as_result(self): pass def test_all_possible_moves_1(self): ''' Print statement to easily get the list of moves in string form. Used for constructing tests. for move in self.board.all_possible_moves(color.white): print("""+ str(move) + "", ", end="") ''' pass def test_all_possible_moves_2(self): pass def test_no_moves(self): pass def test_find_piece(self): pass def test_find_king(self): pass def test_get_king(self): pass def test_remove_piece_at_square(self): pass def test_place_piece_at_square(self): pass def test_move_piece(self): pass def test_update_pawn_moves_one_step(self): pass def test_update_pawn_moves_two_steps(self): pass def test_update_moves_king_side_castle(self): pass
22
1
10
2
7
1
1
0.1
1
3
0
0
21
1
21
93
237
67
155
41
133
15
123
40
101
3
2
2
23
146,854
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_core/test_algebraic/test_converter.py
tests.test_core.test_algebraic.test_converter.TestConverter
class TestConverter(unittest.TestCase): def setUp(self): self.test_board = Board.init_default() self.e_four_move = Move(end_loc=Location.from_string("e4"), piece=Pawn(color.white, Location.from_string("e4")), status=notation_const.MOVEMENT, start_loc=Location.from_string("e2")) def test_short_alg(self): self.assertEqual(converter.short_alg("e4", color.white, self.test_board), self.e_four_move) def test_incomplete_alg_pawn_movement(self): self.assertEqual( converter.incomplete_alg("e4", color.white, self.test_board), Move( end_loc=Location.from_string("e4"), piece=Pawn(color.white, Location.from_string("e4")), status=notation_const.MOVEMENT, start_loc=Location.from_string("e2") ) ) def test_incomplete_alg_piece_movement(self): self.assertEqual( converter.incomplete_alg("Nf3", color.white, self.test_board), Move( end_loc=Location.from_string("f3"), piece=Knight(color.white, Location.from_string("f3")), status=notation_const.MOVEMENT, start_loc=Location.from_string("g1") ) ) def test_incomplete_alg_pawn_capture(self): self.test_board.update(converter.short_alg("e4", color.white, self.test_board)) self.test_board.update(converter.short_alg("d5", color.black, self.test_board)) self.assertEqual( converter.incomplete_alg("exd5", color.white, self.test_board), Move( end_loc=Location.from_string("d5"), piece=Pawn(color.white, Location.from_string("e4")), status=notation_const.CAPTURE, start_loc=Location.from_string("e4") ) ) def test_incomplete_alg_piece_capture(self): self.test_board.update(converter.short_alg("Nf3", color.white, self.test_board)) self.test_board.update(converter.short_alg("e5", color.black, self.test_board)) self.assertEqual( converter.incomplete_alg("Nxe5", color.white, self.test_board), Move( end_loc=Location.from_string("e5"), piece=Knight(color.white, Location.from_string("f3")), status=notation_const.CAPTURE, start_loc=Location.from_string("f3") ) ) def test_incomplete_alg_pawn_promotion(self): self.test_board.move_piece(Location.from_string("a2"), Location.from_string("a7")) self.test_board.remove_piece_at_square(Location.from_string("a8")) self.assertEqual( converter.incomplete_alg("a8=Q", color.white, self.test_board), Move( end_loc=Location.from_string("a8"), piece=Pawn(color.white, Location.from_string("e7")), status=notation_const.PROMOTE, promoted_to_piece=Queen, start_loc=Location.from_string("a7") ) ) def test_incomplete_alg_piece_movement_with_file_specified(self): self.assertEqual( converter.incomplete_alg("gNf3", color.white, self.test_board), Move( end_loc=Location.from_string("f3"), piece=Knight(color.white, Location.from_string("g1")), status=notation_const.MOVEMENT, start_loc=Location.from_string("g1") ) ) def test_incomplete_alg_piece_movement_with_file_specified_alt(self): self.assertEqual( converter.incomplete_alg("Ngf3", color.white, self.test_board), Move( end_loc=Location.from_string("f3"), piece=Knight(color.white, Location.from_string("g1")), status=notation_const.MOVEMENT, start_loc=Location.from_string("g1") ) ) def test_incomplete_alg_piece_movement_with_rank_and_file_specified(self): self.assertEqual( converter.incomplete_alg("e1Nf3", color.white, self.test_board), Move( end_loc=Location.from_string("f3"), piece=Knight(color.white, Location.from_string("e1")), status=notation_const.MOVEMENT, start_loc=Location.from_string("e1") ) ) def test_incomplete_alg_pawn_promotion_with_capture(self): self.test_board.move_piece(Location.from_string("a2"), Location.from_string("a7")) self.assertEqual( converter.incomplete_alg("axb8=R", color.white, self.test_board), Move( end_loc=Location.from_string("b8"), piece=Pawn(color.white, Location.from_string("a7")), status=notation_const.CAPTURE_AND_PROMOTE, promoted_to_piece=Rook, start_loc=Location.from_string("a7") ) )
class TestConverter(unittest.TestCase): def setUp(self): pass def test_short_alg(self): pass def test_incomplete_alg_pawn_movement(self): pass def test_incomplete_alg_piece_movement(self): pass def test_incomplete_alg_pawn_capture(self): pass def test_incomplete_alg_piece_capture(self): pass def test_incomplete_alg_pawn_promotion(self): pass def test_incomplete_alg_piece_movement_with_file_specified(self): pass def test_incomplete_alg_piece_movement_with_file_specified_alt(self): pass def test_incomplete_alg_piece_movement_with_rank_and_file_specified(self): pass def test_incomplete_alg_pawn_promotion_with_capture(self): pass
12
0
10
0
10
0
1
0
1
0
0
0
11
2
11
83
118
10
108
14
96
0
31
14
19
1
2
0
11
146,855
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_pieces/test_bishop.py
tests.test_pieces.test_bishop.TestBishop
class TestBishop(TestCase): def setUp(self): self.board = Board.init_default() def test_no_possible_moves(self): self.assertEqual(len(list(self.board.piece_at_square(Location.from_string("c1")) .possible_moves(self.board))), 0) def test_left_diagonal(self): self.board.update(converter.long_alg("b2b3", self.board)) moves = list(self.board.piece_at_square(Location.from_string("c1")).possible_moves(self.board)) self.assertEqual(len(moves), 2) self.assertEqual(moves[0], converter.long_alg("c1b2", self.board)) self.assertEqual(moves[1], converter.long_alg("c1a3", self.board)) def test_capture(self): self.board.move_piece(Location.from_string("g1"), Location.from_string("g7")) moves = list(self.board.piece_at_square(Location.from_string("f8")).possible_moves(self.board)) self.assertEqual(len(moves), 1) self.assertEqual(moves[0], converter.long_alg("f8g7", self.board)) def test_possible_moves(self): self.board.move_piece(Location.from_string("c1"), Location.from_string("d4")) test_moves = self.board.piece_at_square(Location.from_string("d4")).possible_moves(self.board) real_moves = ["d4e5", "d4f6", "d4g7", "d4c5", "d4b6", "d4a7", "d4e3", "d4c3"] for i, move in enumerate(test_moves): self.assertEqual(str(move), real_moves[i])
class TestBishop(TestCase): def setUp(self): pass def test_no_possible_moves(self): pass def test_left_diagonal(self): pass def test_capture(self): pass def test_possible_moves(self): pass
6
0
5
1
4
0
1
0
1
3
0
0
5
1
5
77
30
7
23
12
17
0
22
12
16
2
2
1
6
146,856
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/king.py
chess_py.pieces.king.King
class King(Piece): def __init__(self, input_color, location): """ Creates a King. :type: input_color: Color :type: location: Location """ super(King, self).__init__(input_color, location) self.has_moved = False self.cardinal_directions = self.cross_fn + self.diag_fn def _symbols(self): return {color.white: "♚", color.black: "♔"} def __str__(self): return "K" def in_check_as_result(self, pos, move): """ Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool """ test = cp(pos) test.update(move) test_king = test.get_king(move.color) return self.loc_adjacent_to_opponent_king(test_king.location, test) def loc_adjacent_to_opponent_king(self, location, position): """ Finds if 2 kings are touching given the position of one of the kings. :type: location: Location :type: position: Board :rtype: bool """ for fn in self.cardinal_directions: try: if isinstance(position.piece_at_square(fn(location)), King) and \ position.piece_at_square(fn(location)).color != self.color: return True except IndexError: pass return False def add(self, func, position): """ Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: position: Board :rtype: gen """ try: if self.loc_adjacent_to_opponent_king(func(self.location), position): return except IndexError: return if position.is_square_empty(func(self.location)): yield self.create_move(func(self.location), notation_const.MOVEMENT) elif position.piece_at_square(func(self.location)).color != self.color: yield self.create_move(func(self.location), notation_const.CAPTURE) def _rook_legal_for_castle(self, rook): """ Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. :type: rook: Rook :rtype: bool """ return rook is not None and \ type(rook) is Rook and \ rook.color == self.color and \ not rook.has_moved def _empty_not_in_check(self, position, direction): """ Checks if set of squares in between ``King`` and ``Rook`` are empty and safe for the king to castle. :type: position: Position :type: direction: function :type: times: int :rtype: bool """ def valid_square(square): return position.is_square_empty(square) and \ not self.in_check(position, square) return valid_square(direction(self.location, 1)) and \ valid_square(direction(self.location, 2)) def add_castle(self, position): """ Adds kingside and queenside castling moves if legal :type: position: Board """ if self.has_moved or self.in_check(position): return if self.color == color.white: rook_rank = 0 else: rook_rank = 7 castle_type = { notation_const.KING_SIDE_CASTLE: { "rook_file": 7, "direction": lambda king_square, times: king_square.shift_right(times) }, notation_const.QUEEN_SIDE_CASTLE: { "rook_file": 0, "direction": lambda king_square, times: king_square.shift_left(times) } } for castle_key in castle_type: castle_dict = castle_type[castle_key] castle_rook = position.piece_at_square(Location(rook_rank, castle_dict["rook_file"])) if self._rook_legal_for_castle(castle_rook) and \ self._empty_not_in_check(position, castle_dict["direction"]): yield self.create_move(castle_dict["direction"](self.location, 2), castle_key) def possible_moves(self, position): """ Generates list of possible moves :type: position: Board :rtype: list """ # Chain used to combine multiple generators for move in itertools.chain(*[self.add(fn, position) for fn in self.cardinal_directions]): yield move for move in self.add_castle(position): yield move def in_check(self, position, location=None): """ Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool """ location = location or self.location for piece in position: if piece is not None and piece.color != self.color: if not isinstance(piece, King): for move in piece.possible_moves(position): if move.end_loc == location: return True else: if self.loc_adjacent_to_opponent_king(piece.location, position): return True return False
class King(Piece): def __init__(self, input_color, location): ''' Creates a King. :type: input_color: Color :type: location: Location ''' pass def _symbols(self): pass def __str__(self): pass def in_check_as_result(self, pos, move): ''' Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool ''' pass def loc_adjacent_to_opponent_king(self, location, position): ''' Finds if 2 kings are touching given the position of one of the kings. :type: location: Location :type: position: Board :rtype: bool ''' pass def add(self, func, position): ''' Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: position: Board :rtype: gen ''' pass def _rook_legal_for_castle(self, rook): ''' Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. :type: rook: Rook :rtype: bool ''' pass def _empty_not_in_check(self, position, direction): ''' Checks if set of squares in between ``King`` and ``Rook`` are empty and safe for the king to castle. :type: position: Position :type: direction: function :type: times: int :rtype: bool ''' pass def valid_square(square): pass def add_castle(self, position): ''' Adds kingside and queenside castling moves if legal :type: position: Board ''' pass def possible_moves(self, position): ''' Generates list of possible moves :type: position: Board :rtype: list ''' pass def in_check_as_result(self, pos, move): ''' Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool ''' pass
13
9
13
2
7
4
3
0.62
1
6
2
0
11
2
11
24
167
31
84
26
71
52
65
26
52
7
1
5
31
146,857
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/core/algebraic/location.py
chess_py.core.algebraic.location.Direction
class Direction: UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3
class Direction: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
5
0
5
5
4
0
5
5
4
0
0
0
0
146,858
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/core/algebraic/location.py
chess_py.core.algebraic.location.Location
class Location: def __init__(self, rank, file): """ Creates a location on a chessboard given x and y coordinates. :type: rank: int :type: file: int """ if rank < 0 or rank > 7 or file < 0 or file > 7: raise IndexError("Location must be on the board") self._rank = rank self._file = file @classmethod def from_string(cls, alg_str): """ Creates a location from a two character string consisting of the file then rank written in algebraic notation. Examples: e4, b5, a7 :type: alg_str: str :rtype: Location """ try: return cls(int(alg_str[1]) - 1, ord(alg_str[0]) - 97) except ValueError as e: raise ValueError("Location.from_string {} invalid: {}".format(alg_str, e)) @property def rank(self): return self._rank @property def file(self): return self._file def __key(self): return self.rank, self.file def __hash__(self): return hash(self.__key()) def __eq__(self, other): """ Tests to see if both locations are the same ie rank and file is the same. :type: other: Location """ if not isinstance(other, self.__class__): raise TypeError("Cannot compare other types with Location") return int(self.rank) == int(other.rank) and \ int(self.file) == int(other.file) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "Location({}, {} ({}))".format(self._rank, self._file, str(self)) def __str__(self): """ Finds string representation of Location in algebraic form ie "e4" :rtype: str """ if self._rank is None: rank_str = "" else: rank_str = str(self._rank + 1) if self._file is None: file_str = "" else: file_str = chr(self._file + 97) return file_str + rank_str def on_board(self): """ Returns if the move is on the board or not. If the rank and file are both in between 0 and 7, this method will return True. :rtype: bool """ if -1 < self._rank < 8 and \ -1 < self._file < 8: return True return False def shift(self, direction): """ Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location """ try: if direction == Direction.UP: return self.shift_up() elif direction == Direction.DOWN: return self.shift_down() elif direction == Direction.RIGHT: return self.shift_right() elif direction == Direction.LEFT: return self.shift_left() else: raise IndexError("Invalid direction {}".format(direction)) except IndexError as e: raise IndexError(e) def shift_up(self, times=1): """ Finds Location shifted up by 1 :rtype: Location """ try: return Location(self._rank + times, self._file) except IndexError as e: raise IndexError(e) def shift_down(self, times=1): """ Finds Location shifted down by 1 :rtype: Location """ try: return Location(self._rank - times, self._file) except IndexError as e: raise IndexError(e) def shift_forward(self, ref_color, times=1): direction = 1 if ref_color == color.white else -1 try: return Location(self._rank + times*direction, self._file) except IndexError as e: raise IndexError(e) def shift_back(self, ref_color, times=1): direction = -1 if ref_color == color.white else 1 try: return Location(self._rank + times*direction, self._file) except IndexError as e: raise IndexError(e) def shift_right(self, times=1): """ Finds Location shifted right by 1 :rtype: Location """ try: return Location(self._rank, self._file + times) except IndexError as e: raise IndexError(e) def shift_left(self, times=1): """ Finds Location shifted left by 1 :rtype: Location """ try: return Location(self._rank, self._file - times) except IndexError as e: raise IndexError(e) def shift_up_right(self, times=1): """ Finds Location shifted up right by 1 :rtype: Location """ try: return Location(self._rank + times, self._file + times) except IndexError as e: raise IndexError(e) def shift_up_left(self, times=1): """ Finds Location shifted up left by 1 :rtype: Location """ try: return Location(self._rank + times, self._file - times) except IndexError as e: raise IndexError(e) def shift_down_right(self, times=1): """ Finds Location shifted down right by 1 :rtype: Location """ try: return Location(self._rank - times, self._file + times) except IndexError as e: raise IndexError(e) def shift_down_left(self, times=1): """ Finds Location shifted down left by 1 :rtype: Location """ try: return Location(self._rank - times, self._file - times) except IndexError as e: raise IndexError(e)
class Location: def __init__(self, rank, file): ''' Creates a location on a chessboard given x and y coordinates. :type: rank: int :type: file: int ''' pass @classmethod def from_string(cls, alg_str): ''' Creates a location from a two character string consisting of the file then rank written in algebraic notation. Examples: e4, b5, a7 :type: alg_str: str :rtype: Location ''' pass @property def rank(self): pass @property def file(self): pass def __key(self): pass def __hash__(self): pass def __eq__(self, other): ''' Tests to see if both locations are the same ie rank and file is the same. :type: other: Location ''' pass def __ne__(self, other): pass def __repr__(self): pass def __str__(self): ''' Finds string representation of Location in algebraic form ie "e4" :rtype: str ''' pass def on_board(self): ''' Returns if the move is on the board or not. If the rank and file are both in between 0 and 7, this method will return True. :rtype: bool ''' pass def shift(self, direction): ''' Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location ''' pass def shift_up(self, times=1): ''' Finds Location shifted up by 1 :rtype: Location ''' pass def shift_down(self, times=1): ''' Finds Location shifted down by 1 :rtype: Location ''' pass def shift_forward(self, ref_color, times=1): pass def shift_back(self, ref_color, times=1): pass def shift_right(self, times=1): ''' Finds Location shifted right by 1 :rtype: Location ''' pass def shift_left(self, times=1): ''' Finds Location shifted left by 1 :rtype: Location ''' pass def shift_up_right(self, times=1): ''' Finds Location shifted up right by 1 :rtype: Location ''' pass def shift_up_left(self, times=1): ''' Finds Location shifted up left by 1 :rtype: Location ''' pass def shift_down_right(self, times=1): ''' Finds Location shifted down right by 1 :rtype: Location ''' pass def shift_down_left(self, times=1): ''' Finds Location shifted down left by 1 :rtype: Location ''' pass
26
14
9
1
5
3
2
0.58
0
6
1
0
21
2
22
22
218
41
112
44
86
65
101
29
78
6
0
2
45
146,859
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_core/test_color.py
tests.test_core.test_color.TestColor
class TestColor(TestCase): def test_opponent(self): self.assertEqual(-color.white, color.black) self.assertEqual(-color.black, color.white)
class TestColor(TestCase): def test_opponent(self): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
73
5
1
4
2
2
0
4
2
2
1
2
0
1
146,860
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_core/test_algebraic/test_location.py
tests.test_core.test_algebraic.test_location.TestLocation
class TestLocation(unittest.TestCase): def testEquals(self): self.assertEqual(Location(2, 3), Location(2, 3)) self.assertEqual(Location(7, 6), Location(7, 6)) self.assertNotEqual(Location(4, 5), Location(5, 4)) def testStr(self): self.assertEqual(str(Location(3, 4)), "e4") self.assertEqual(str(Location(0, 0)), "a1") self.assertEqual(str(Location(7, 7)), "h8") def testShiftUp(self): self.assertEqual(Location(3, 4).shift_up(), Location(4, 4)) self.assertEqual(Location(0, 2).shift_up(), Location(1, 2)) def testShiftDown(self): self.assertEqual(Location(3, 4).shift_down(), Location(2, 4)) self.assertEqual(Location(1, 2).shift_down(), Location(0, 2)) def testShiftRight(self): self.assertEqual(Location(3, 4).shift_right(), Location(3, 5)) self.assertEqual(Location(0, 2).shift_right(), Location(0, 3)) def testShiftLeft(self): self.assertEqual(Location(3, 4).shift_left(), Location(3, 3)) self.assertEqual(Location(0, 2).shift_left(), Location(0, 1)) def testShiftUpRight(self): self.assertEqual(Location(3, 4).shift_up_right(), Location(4, 5)) def testShiftUpLeft(self): self.assertEqual(Location(1, 2).shift_up_left(), Location(2, 1)) def testShiftDownRight(self): self.assertEqual(Location(5, 3).shift_down_right(), Location(4, 4)) def testShiftDownLeft(self): self.assertEqual(Location(1, 1).shift_down_left(), Location(0, 0))
class TestLocation(unittest.TestCase): def testEquals(self): pass def testStr(self): pass def testShiftUp(self): pass def testShiftDown(self): pass def testShiftRight(self): pass def testShiftLeft(self): pass def testShiftUpRight(self): pass def testShiftUpLeft(self): pass def testShiftDownRight(self): pass def testShiftDownLeft(self): pass
11
0
3
0
3
0
1
0
1
1
0
0
10
0
10
82
39
10
29
11
18
0
29
11
18
1
2
0
10
146,861
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/core/algebraic/move.py
chess_py.core.algebraic.move.Move
class Move: def __init__(self, end_loc, piece, status, start_loc, promoted_to_piece=None): """ Constructor to create move using ``Location`` :type: end_loc: Location :type: piece: Piece :type: status: int """ self._end_loc = end_loc self._status = status self._piece = piece self._start_loc = start_loc self.color = piece.color self.promoted_to_piece = promoted_to_piece @property def end_loc(self): return self._end_loc @property def status(self): return self._status @property def piece(self): return self._piece def __key(self): return self.end_loc, \ self.piece, \ self.status, \ self.start_loc, \ self.promoted_to_piece def __hash__(self): return hash(self.__key()) def __eq__(self, other): """ Finds if move is same move as this one. :type: other: Move """ if not isinstance(other, self.__class__): raise TypeError("Cannot compare type {} with Move".format(type(other))) for index, item in enumerate(self.__key()): if not self._check_equals_or_none(item, other.__key()[index]): return False return True @staticmethod def _check_equals_or_none(var1, var2): """ If either is None then return True, otherwise compare them and return if they are equal. :type: var1: object :type: var2: object :rtype: bool """ if var1 is None or var2 is None: return True return var1 == var2 def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "Move({})".format(self.__dict__) def __str__(self): """ Finds string representation in long algebraic notation :rtype: str """ move_str = str(self._start_loc) + str(self._end_loc) if self.promoted_to_piece is not None: move_str += str(self.promoted_to_piece) return move_str @property def start_loc(self): """ Finds start Location of move if specified. Otherwise throws an AttributeError :rtype: Location """ return self._start_loc def would_move_be_promotion(self): """ Finds if move from current location would be a promotion """ return (self._end_loc.rank == 0 and not self.color) or \ (self._end_loc.rank == 7 and self.color)
class Move: def __init__(self, end_loc, piece, status, start_loc, promoted_to_piece=None): ''' Constructor to create move using ``Location`` :type: end_loc: Location :type: piece: Piece :type: status: int ''' pass @property def end_loc(self): pass @property def status(self): pass @property def piece(self): pass def __key(self): pass def __hash__(self): pass def __eq__(self, other): ''' Finds if move is same move as this one. :type: other: Move ''' pass @staticmethod def _check_equals_or_none(var1, var2): ''' If either is None then return True, otherwise compare them and return if they are equal. :type: var1: object :type: var2: object :rtype: bool ''' pass def __ne__(self, other): pass def __repr__(self): pass def __str__(self): ''' Finds string representation in long algebraic notation :rtype: str ''' pass @property def start_loc(self): ''' Finds start Location of move if specified. Otherwise throws an AttributeError :rtype: Location ''' pass def would_move_be_promotion(self): ''' Finds if move from current location would be a promotion ''' pass
19
6
7
1
4
2
1
0.53
0
4
0
0
12
6
13
13
108
21
57
32
33
30
42
22
28
4
0
2
18
146,862
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/pieces/bishop.py
chess_py.pieces.bishop.Bishop
class Bishop(Rook, Piece): def __init__(self, input_color, location): """ Creates Bishop object that can be compared to and return possible moves :type: input_color: Color """ Piece.__init__(self, input_color, location) def _symbols(self): return {color.white: "♝", color.black: "♗"} def __str__(self): return "B" def possible_moves(self, position): """ Returns all possible bishop moves. :type: position: Board :rtype: list """ for move in itertools.chain(*[self.moves_in_direction(fn, position) for fn in self.diag_fn]): yield move
class Bishop(Rook, Piece): def __init__(self, input_color, location): ''' Creates Bishop object that can be compared to and return possible moves :type: input_color: Color ''' pass def _symbols(self): pass def __str__(self): pass def possible_moves(self, position): ''' Returns all possible bishop moves. :type: position: Board :rtype: list ''' pass
5
2
5
1
2
2
1
0.9
2
1
0
2
4
0
4
22
25
6
10
6
5
9
10
6
5
2
2
1
5
146,863
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_pieces/test_pawn.py
tests.test_pieces.test_pawn.TestPawn
class TestPawn(TestCase): def setUp(self): self.position = Board.init_default() self.white_pawn = Pawn(color.white, Location.from_string("e2")) self.position.place_piece_at_square(self.white_pawn, Location.from_string("e2")) self.black_pawn = Pawn(color.black, Location.from_string("a7")) self.position.place_piece_at_square(self.black_pawn, Location.from_string("a7")) def test_square_in_front(self): self.assertEqual(self.white_pawn.square_in_front(self.white_pawn.location), Location.from_string("e3")) self.assertEqual(self.black_pawn.square_in_front(self.black_pawn.location), Location.from_string("a6")) def test_two_squares_in_front(self): self.assertEqual(self.white_pawn.two_squares_in_front(self.white_pawn.location), Location.from_string("e4")) self.assertEqual(self.black_pawn.two_squares_in_front(self.black_pawn.location), Location.from_string("a5")) def test_would_move_be_promotion(self): self.assertTrue(self.white_pawn.would_move_be_promotion(Location.from_string("e7"))) self.assertTrue(self.black_pawn.would_move_be_promotion(Location.from_string("a2"))) self.assertFalse(self.white_pawn.would_move_be_promotion(Location.from_string("e2"))) self.assertFalse(self.black_pawn.would_move_be_promotion(Location.from_string("a7"))) def test_create_promotion_moves(self): self.white_pawn.location = Location.from_string("e7") moves = list(self.white_pawn.create_promotion_moves(notation_const.CAPTURE, Location.from_string("e7"))) self.assertEqual(len(list(moves)), 4) self.assertEqual(moves[0].start_loc, Location.from_string("e7")) self.assertEqual(moves[0].promoted_to_piece, Queen) self.assertEqual(moves[1].promoted_to_piece, Rook) self.assertEqual(moves[2].promoted_to_piece, Bishop) self.assertEqual(moves[3].promoted_to_piece, Knight) def test_forward_moves(self): self.white_pawn.location = Location.from_string("e2") moves = list(self.white_pawn.forward_moves(self.position)) self.assertEqual(len(moves), 2) self.assertEqual(moves[0], Move(end_loc=self.white_pawn.square_in_front(self.white_pawn.location), piece=self.white_pawn, status=notation_const.MOVEMENT, start_loc=self.white_pawn.location)) self.assertEqual(moves[1], Move(end_loc=self.white_pawn.square_in_front(self.white_pawn.square_in_front(self.white_pawn.location)), piece=self.white_pawn, status=notation_const.MOVEMENT, start_loc=self.white_pawn.location)) moves = list(self.black_pawn.forward_moves(self.position)) self.assertEqual(len(moves), 2) self.assertEqual(moves[0], Move(end_loc=self.black_pawn.square_in_front(self.black_pawn.location), piece=self.black_pawn, status=notation_const.MOVEMENT, start_loc=self.black_pawn.location)) self.assertEqual(moves[1], Move(end_loc=self.black_pawn.square_in_front(self.black_pawn.square_in_front(self.black_pawn.location)), piece=self.black_pawn, status=notation_const.MOVEMENT, start_loc=self.black_pawn.location)) def test_capture_moves(self): self.position.move_piece(Location.from_string("d7"), Location.from_string("d5")) self.position.move_piece(Location.from_string("e2"), Location.from_string("e4")) black_pawn = self.position.piece_at_square(Location.from_string("d5")) move = list(self.white_pawn.capture_moves(self.position)) self.assertEqual(len(move), 1) self.assertEqual(move[0], Move(end_loc=black_pawn.location, piece=self.white_pawn, status=notation_const.CAPTURE, start_loc=self.white_pawn.location)) def test_en_passant_moves(self): self.position.move_piece(Location.from_string("d7"), Location.from_string("d4")) self.position.move_piece(Location.from_string("e2"), Location.from_string("e4")) black_pawn = self.position.piece_at_square(Location.from_string("d4")) self.position.piece_at_square(Location.from_string("e4")).just_moved_two_steps = True move = list(black_pawn.en_passant_moves(self.position)) self.assertEqual(len(move), 1) self.assertEqual(move[0], Move(end_loc=black_pawn.square_in_front(black_pawn.location.shift_right()), piece=black_pawn, status=notation_const.EN_PASSANT, start_loc=black_pawn.location)) def test_possible_moves(self): self.assertEqual(len(list(self.white_pawn.possible_moves(self.position))), 2) self.position.move_piece(Location.from_string("e2"), Location.from_string("e3")) self.assertEqual(len(list(self.white_pawn.possible_moves(self.position))), 1)
class TestPawn(TestCase): def setUp(self): pass def test_square_in_front(self): pass def test_two_squares_in_front(self): pass def test_would_move_be_promotion(self): pass def test_create_promotion_moves(self): pass def test_forward_moves(self): pass def test_capture_moves(self): pass def test_en_passant_moves(self): pass def test_possible_moves(self): pass
10
0
10
2
8
0
1
0
1
1
0
0
9
3
9
81
97
22
75
19
65
0
56
19
46
1
2
0
9
146,864
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_pieces/test_knight.py
tests.test_pieces.test_knight.TestKnight
class TestKnight(TestCase): def setUp(self): self.empty_pos = Board([[None for _ in range(8)] for _ in range(8)]) def test_possible_moves(self): self.empty_pos.place_piece_at_square(Knight(color.white, Location.from_string("e4")), Location.from_string("e4")) knight = self.empty_pos.piece_at_square(Location.from_string("e4")) moves = knight.possible_moves(self.empty_pos) self.assertEqual(len(list(moves)), 8)
class TestKnight(TestCase): def setUp(self): pass def test_possible_moves(self): pass
3
0
4
1
4
0
1
0
1
2
0
0
2
1
2
74
10
2
8
6
5
0
8
6
5
1
2
0
2
146,865
LordDarkula/chess_py
LordDarkula_chess_py/tests/test_pieces/test_king.py
tests.test_pieces.test_king.TestKing
class TestKing(TestCase): def setUp(self): self.board = Board.init_default() def test_in_check_as_result(self): self.assertFalse(self.board.get_king(color.white).in_check_as_result(self.board, converter.long_alg("e2e4", self.board))) self.board.move_piece(Location.from_string("e1"), Location.from_string("e3")) self.board.move_piece(Location.from_string("e8"), Location.from_string("e5")) # self.assertTrue(self.board.get_king(color.white).in_check_as_result(self.board, converter.long_alg("e3e4", self.board))) def test_add(self): self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_up(), self.board))), 0) self.board.update(converter.long_alg("e2e4", self.board)) # King should be able to move up self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_up(), self.board))), 1) # King should not be able to move down self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_down(), self.board))), 0) # King should not be able to move left self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_left(), self.board))), 0) # King should not be able to move right self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_right(), self.board))), 0) # King should not be able to move up left self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_up_left(), self.board))), 0) # King should not be able to move down right self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_down_right(), self.board))), 0) # King should not be able to move down left self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_down_left(), self.board))), 0) # King should not be able to move up right self.assertEqual( len(list(self.board.get_king(color.white).add(lambda x: x.shift_up_right(), self.board))), 0) def test_kingside_castle(self): self.board.update(converter.short_alg("e4", color.white, self.board)) self.board.update(converter.short_alg("Nf3", color.white, self.board)) self.board.update(converter.short_alg("Be2", color.white, self.board)) castle_move = Move( end_loc=Location.from_string("g1"), piece=King(color.white, Location.from_string("g1")), status=notation_const.KING_SIDE_CASTLE, start_loc=Location.from_string("e1") ) self.assertEqual( list(self.board.get_king(color.white).add_castle(self.board))[0], castle_move) def test_queenside_castle(self): self.board.remove_piece_at_square(Location.from_string("b1")) self.board.remove_piece_at_square(Location.from_string("c1")) self.board.remove_piece_at_square(Location.from_string("d1")) castle_move = Move( end_loc=Location.from_string("c1"), piece=King(color.white, Location.from_string("c1")), status=notation_const.QUEEN_SIDE_CASTLE, start_loc=Location.from_string("e1") ) self.assertEqual( list(self.board.get_king(color.white).add_castle(self.board))[0], castle_move) def test_possible_moves(self): self.board = Board([[None for _ in range(8)] for _ in range(8)]) my_king = King(color.white, Location.from_string("f3")) self.board.place_piece_at_square(my_king, Location.from_string("f3")) moves = ['f3f4', 'f3g3', 'f3f2', 'f3e3', 'f3g4', 'f3e4', 'f3g2', 'f3e2'] for i, move in enumerate(my_king.possible_moves(self.board)): self.assertEqual(move, converter.long_alg(moves[i], self.board)) def test_in_check(self): self.board = Board([[None for _ in range(8)] for _ in range(8)]) my_king = King(color.white, Location.from_string("f3")) self.board.place_piece_at_square(my_king, Location.from_string("f3")) self.board.place_piece_at_square(Rook(color.black, Location.from_string("f1")), Location.from_string("f1")) print(self.board.piece_at_square(Location.from_string("f1")).color) print(self.board) print(my_king.color) print(color.white == color.black) self.assertTrue(my_king.in_check(self.board)) self.board = Board.init_default() self.board.update(converter.long_alg("f2f3", self.board)) self.board.move_piece(Location.from_string("d8"), Location.from_string("g3")) self.assertTrue(self.board.get_king(color.white).in_check(self.board))
class TestKing(TestCase): def setUp(self): pass def test_in_check_as_result(self): pass def test_add(self): pass def test_kingside_castle(self): pass def test_queenside_castle(self): pass def test_possible_moves(self): pass def test_in_check_as_result(self): pass
8
0
16
3
12
1
1
0.11
1
3
0
0
7
1
7
79
118
27
82
17
74
9
51
15
43
2
2
1
8
146,866
LordDarkula/chess_py
LordDarkula_chess_py/chess_py/core/board.py
chess_py.core.board.Board
class Board: """ Standard starting position in a chess game. Initialized upon startup and is used when init_default constructor is used """ def __init__(self, position): """ Creates a ``Board`` given an array of ``Piece`` and ``None`` objects to represent the given position of the board. :type: position: list """ self.position = position self.possible_moves = dict() try: self.king_loc_dict = {white: self.find_king(white), black: self.find_king(black)} except ValueError: self.king_loc_dict = None @classmethod def init_default(cls): """ Creates a ``Board`` with the standard chess starting position. :rtype: Board """ return cls([ # First rank [Rook(white, Location(0, 0)), Knight(white, Location(0, 1)), Bishop(white, Location(0, 2)), Queen(white, Location(0, 3)), King(white, Location(0, 4)), Bishop(white, Location(0, 5)), Knight(white, Location(0, 6)), Rook(white, Location(0, 7))], # Second rank [Pawn(white, Location(1, file)) for file in range(8)], # Third rank [None for _ in range(8)], # Fourth rank [None for _ in range(8)], # Fifth rank [None for _ in range(8)], # Sixth rank [None for _ in range(8)], # Seventh rank [Pawn(black, Location(6, file)) for file in range(8)], # Eighth rank [Rook(black, Location(7, 0)), Knight(black, Location(7, 1)), Bishop(black, Location(7, 2)), Queen(black, Location(7, 3)), King(black, Location(7, 4)), Bishop(black, Location(7, 5)), Knight(black, Location(7, 6)), Rook(black, Location(7, 7))] ]) @property def position_tuple(self): return ((str(piece) for piece in self.position[index]) for index, row in enumerate(self.position)) def __key(self): return self.position def __hash__(self): return hash(tuple([hash(piece) for piece in self])) def __eq__(self, other): if not isinstance(other, self.__class__): raise TypeError("Cannot compare other type to Board") for i, row in enumerate(self.position): for j, piece in enumerate(row): if piece != other.position[i][j]: return False return True def __ne__(self, other): return not self.__eq__(other) def __str__(self): board_string = "" for i, row in enumerate(self.position): board_string += str(8 - i) + " " for j, square in enumerate(row): piece = self.piece_at_square(Location(7 - i, j)) if isinstance(piece, Piece): board_string += piece.symbol + " " else: board_string += "_ " board_string += "\n" board_string += " a b c d e f g h" return board_string def __iter__(self): for row in self.position: for square in row: yield square def __copy__(self): """ Copies the board faster than deepcopy :rtype: Board """ return Board([[cp(piece) or None for piece in self.position[index]] for index, row in enumerate(self.position)]) def piece_at_square(self, location): """ Finds the chess piece at a square of the position. :type: location: Location :rtype: Piece """ return self.position[location.rank][location.file] def is_square_empty(self, location): """ Finds whether a chess piece occupies a square of the position. :type: location: Location :rtype: bool """ return self.position[location.rank][location.file] is None def material_advantage(self, input_color, val_scheme): """ Finds the advantage a particular side possesses given a value scheme. :type: input_color: Color :type: val_scheme: PieceValues :rtype: double """ if self.get_king(input_color).in_check(self) and self.no_moves(input_color): return -100 if self.get_king(-input_color).in_check(self) and self.no_moves(-input_color): return 100 return sum([val_scheme.val(piece, input_color) for piece in self]) def advantage_as_result(self, move, val_scheme): """ Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double """ test_board = cp(self) test_board.update(move) return test_board.material_advantage(move.color, val_scheme) def all_possible_moves(self, input_color): """ Checks if all the possible moves has already been calculated and is stored in `possible_moves` dictionary. If not, it is calculated with `_calc_all_possible_moves`. :type: input_color: Color :rtype: list """ position_tuple = self.position_tuple if position_tuple not in self.possible_moves: self.possible_moves[position_tuple] = tuple(self._calc_all_possible_moves(input_color)) return self.possible_moves[position_tuple] def _calc_all_possible_moves(self, input_color): """ Returns list of all possible moves :type: input_color: Color :rtype: list """ for piece in self: # Tests if square on the board is not empty if piece is not None and piece.color == input_color: for move in piece.possible_moves(self): test = cp(self) test_move = Move(end_loc=move.end_loc, piece=test.piece_at_square(move.start_loc), status=move.status, start_loc=move.start_loc, promoted_to_piece=move.promoted_to_piece) test.update(test_move) if self.king_loc_dict is None: yield move continue my_king = test.piece_at_square(self.king_loc_dict[input_color]) if my_king is None or \ not isinstance(my_king, King) or \ my_king.color != input_color: self.king_loc_dict[input_color] = test.find_king(input_color) my_king = test.piece_at_square(self.king_loc_dict[input_color]) if not my_king.in_check(test): yield move def runInParallel(*fns): """ Runs multiple processes in parallel. :type: fns: def """ proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join() def no_moves(self, input_color): # Loops through columns for piece in self: # Tests if square on the board is not empty if piece is not None and piece.color == input_color: for move in piece.possible_moves(self): test = cp(self) test.update(move) if not test.get_king(input_color).in_check(test): return False return True def find_piece(self, piece): """ Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type: piece: Piece :rtype: Location """ for i, _ in enumerate(self.position): for j, _ in enumerate(self.position): loc = Location(i, j) if not self.is_square_empty(loc) and \ self.piece_at_square(loc) == piece: return loc raise ValueError("{} \nPiece not found: {}".format(self, piece)) def get_piece(self, piece_type, input_color): """ Gets location of a piece on the board given the type and color. :type: piece_type: Piece :type: input_color: Color :rtype: Location """ for loc in self: piece = self.piece_at_square(loc) if not self.is_square_empty(loc) and \ isinstance(piece, piece_type) and \ piece.color == input_color: return loc raise Exception("{} \nPiece not found: {}".format(self, piece_type)) def find_king(self, input_color): """ Finds the Location of the King of input_color :type: input_color: Color :rtype: Location """ return self.find_piece(King(input_color, Location(0, 0))) def get_king(self, input_color): """ Returns King of input_color :type: input_color: Color :rtype: King """ return self.piece_at_square(self.find_king(input_color)) def remove_piece_at_square(self, location): """ Removes piece at square :type: location: Location """ self.position[location.rank][location.file] = None def place_piece_at_square(self, piece, location): """ Places piece at given get_location :type: piece: Piece :type: location: Location """ self.position[location.rank][location.file] = piece piece.location = location def move_piece(self, initial, final): """ Moves piece from one location to another :type: initial: Location :type: final: Location """ self.place_piece_at_square(self.piece_at_square(initial), final) self.remove_piece_at_square(initial) def update(self, move): """ Updates position by applying selected move :type: move: Move """ if move is None: raise TypeError("Move cannot be type None") if self.king_loc_dict is not None and isinstance(move.piece, King): self.king_loc_dict[move.color] = move.end_loc # Invalidates en-passant for square in self: pawn = square if isinstance(pawn, Pawn): pawn.just_moved_two_steps = False # Sets King and Rook has_moved property to True is piece has moved if type(move.piece) is King or type(move.piece) is Rook: move.piece.has_moved = True elif move.status == notation_const.MOVEMENT and \ isinstance(move.piece, Pawn) and \ fabs(move.end_loc.rank - move.start_loc.rank) == 2: move.piece.just_moved_two_steps = True if move.status == notation_const.KING_SIDE_CASTLE: self.move_piece(Location(move.end_loc.rank, 7), Location(move.end_loc.rank, 5)) self.piece_at_square(Location(move.end_loc.rank, 5)).has_moved = True elif move.status == notation_const.QUEEN_SIDE_CASTLE: self.move_piece(Location(move.end_loc.rank, 0), Location(move.end_loc.rank, 3)) self.piece_at_square(Location(move.end_loc.rank, 3)).has_moved = True elif move.status == notation_const.EN_PASSANT: self.remove_piece_at_square(Location(move.start_loc.rank, move.end_loc.file)) elif move.status == notation_const.PROMOTE or \ move.status == notation_const.CAPTURE_AND_PROMOTE: try: self.remove_piece_at_square(move.start_loc) self.place_piece_at_square(move.promoted_to_piece(move.color, move.end_loc), move.end_loc) except TypeError as e: raise ValueError("Promoted to piece cannot be None in Move {}\n{}".format(repr(move), e)) return self.move_piece(move.piece.location, move.end_loc)
class Board: ''' Standard starting position in a chess game. Initialized upon startup and is used when init_default constructor is used ''' def __init__(self, position): ''' Creates a ``Board`` given an array of ``Piece`` and ``None`` objects to represent the given position of the board. :type: position: list ''' pass @classmethod def init_default(cls): ''' Creates a ``Board`` with the standard chess starting position. :rtype: Board ''' pass @property def position_tuple(self): pass def __key(self): pass def __hash__(self): pass def __eq__(self, other): pass def __ne__(self, other): pass def __str__(self): pass def __iter__(self): pass def __copy__(self): ''' Copies the board faster than deepcopy :rtype: Board ''' pass def piece_at_square(self, location): ''' Finds the chess piece at a square of the position. :type: location: Location :rtype: Piece ''' pass def is_square_empty(self, location): ''' Finds whether a chess piece occupies a square of the position. :type: location: Location :rtype: bool ''' pass def material_advantage(self, input_color, val_scheme): ''' Finds the advantage a particular side possesses given a value scheme. :type: input_color: Color :type: val_scheme: PieceValues :rtype: double ''' pass def advantage_as_result(self, move, val_scheme): ''' Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double ''' pass def all_possible_moves(self, input_color): ''' Checks if all the possible moves has already been calculated and is stored in `possible_moves` dictionary. If not, it is calculated with `_calc_all_possible_moves`. :type: input_color: Color :rtype: list ''' pass def _calc_all_possible_moves(self, input_color): ''' Returns list of all possible moves :type: input_color: Color :rtype: list ''' pass def runInParallel(*fns): ''' Runs multiple processes in parallel. :type: fns: def ''' pass def no_moves(self, input_color): pass def find_piece(self, piece): ''' Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type: piece: Piece :rtype: Location ''' pass def get_piece(self, piece_type, input_color): ''' Gets location of a piece on the board given the type and color. :type: piece_type: Piece :type: input_color: Color :rtype: Location ''' pass def find_king(self, input_color): ''' Finds the Location of the King of input_color :type: input_color: Color :rtype: Location ''' pass def get_king(self, input_color): ''' Returns King of input_color :type: input_color: Color :rtype: King ''' pass def remove_piece_at_square(self, location): ''' Removes piece at square :type: location: Location ''' pass def place_piece_at_square(self, piece, location): ''' Places piece at given get_location :type: piece: Piece :type: location: Location ''' pass def move_piece(self, initial, final): ''' Moves piece from one location to another :type: initial: Location :type: final: Location ''' pass def update(self, move): ''' Updates position by applying selected move :type: move: Move ''' pass
29
19
13
2
7
4
3
0.6
0
18
9
0
25
3
26
26
378
89
181
64
152
108
146
58
119
12
0
4
67
146,867
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/amqp/rpc.py
chaos.amqp.rpc.Rpc
class Rpc(Queue): """ Attempts to simplify RPC style calls using AMQP exchanges and queues. This works two-fold: * This class will create an Exchange for sending RPC messages. * This class will also create a Queue for handling responses to the RPC messages. Additionally, this class can also create a 'normal' Queue, to avoid having to create a separate instance. All of the above is created using a single AMQP channel. """ def __init__(self, host, credentials, identifier=None, prefetch_count=1, exchange=None, auto_delete=True, queue=None, binds=None, confirm_delivery=False): """ Initialize AMQP connection. Parameters ---------- host: tuple Must contain hostname and port to use for connection credentials: tuple Must contain username and password for this connection identifier: string Identifier for this RPC Queue. This parameter determines what the incoming queue will be called. If left as None, an identifier will be generated. prefetch_count: int Set the prefetch_count of all queues defined by this class. exchange: string If set, this RPC queue will also be bound to the given exchange using the identifier as routing key. If not, we will only be implicitly bound to the default exchange auto_delete: boolean Set to True to automatically delete the created RPC queue. queue: dict Create a separate queue based on the given parameters. This is a general purpose AMQP queue, and can be provided a separate callback using consume(). Must contain at least the following keys: queue: string - what queue to use passive: boolean - should we use an existing queue, to try to declare our own Options below are optional when passive = True durable: boolean - should the queue be durable auto_delete: boolean - should we auto delete the queue when we close the connection binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind confirm_delivery: boolean If True, basic.Confirm will be set on the current channel. """ self.logger = logging.getLogger(__name__) self.rpc_queue_name = identifier if not self.rpc_queue_name: self.rpc_queue_name = "rpc.{0}".format(int(time.time())) rpc_queue = { "queue": self.rpc_queue_name, "passive": False, "durable": False, "auto_delete": auto_delete } if exchange: binds.append({"queue": self.rpc_queue_name, "exchange": exchange, "routing_key": self.rpc_queue_name}) super(Rpc, self).__init__(host, credentials, rpc_queue, None) if queue: self.queue_name = queue['queue'] self.logger.info( "Declaring general purpose queue {0}".format(self.queue_name)) self.channel.queue_declare(**queue) else: del (self.queue_name) if binds: self._perform_binds(binds) self.channel.basic_qos(prefetch_count=prefetch_count) if confirm_delivery: self.channel.confirm_delivery() self.responses = {} def consume(self, consumer_callback=None, exclusive=False): """ Initialize consuming of messages from an AMQP RPC queue. Messages will be consumed after start_consuming() is called. An internal callback will be used to handle incoming RPC responses. Only responses that have been registered with register_response() will be kept internally, all other responses will be dropped silently. Responses can be accessed by using get_response(). The internal callback will assume that the incoming RPC responses will have a correlation_id property set in the headers. Additionally, if a general purpose queue was created on construction, the parameters to this function can be used to declare a callback and options for that queue. A ValueError is raised when trying to set a general purpose callback, but no queue was declared during construction. In contrast to the Queue class, the recover parameter is missing from this implementation of consume(). We will always try to requeue old messages. Parameters ---------- consumer_callback: callback Function to call when a message is consumed. The callback function will be called on each delivery, and will receive three parameters: * channel * method_frame * header_frame * body exclusive: boolean Is this consumer supposed to be the exclusive consumer of the given queue? """ if not hasattr(self, "queue_name") and consumer_callback: raise ValueError( "Trying to set a callback, while no general purpose queue was declared.") self.rpc_consumer_tag = self.channel.basic_consume( consumer_callback=self._rpc_response_callback, queue=self.rpc_queue_name, exclusive=False) if consumer_callback: super(Rpc, self).consume(consumer_callback, exclusive, True) def _rpc_response_callback(self, channel, method_frame, header_frame, body): """ Internal callback used by consume() Parameters ---------- channel: object Channel from which the callback originated method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message """ self.logger.debug("Received RPC response with correlation_id: {0}".format( header_frame.correlation_id)) if header_frame.correlation_id in self.responses: self.responses[header_frame.correlation_id] = { "method_frame": method_frame, "header_frame": header_frame, "body": body } channel.basic_ack(method_frame.delivery_tag) def register_response(self, correlation_id=None): """ Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generating correlation_ids. Depending on the underlying system and implementation, this will guarantee that generated values are unique between workers. At least CPython guarantees this behaviour. Parameters ---------- correlation_id: string Identifier under which to expect a RPC callback. If None, a correlation_id will be generated. """ if not correlation_id: correlation_id = str(uuid.uuid1()) if correlation_id in self.responses: raise KeyError( "Correlation_id {0} was already registered, and therefor not unique.".format(correlation_id)) self.responses[correlation_id] = None return correlation_id def retrieve_available_responses(self): """ Retrieve a list of all available responses. Will return a list of correlation_ids. """ return [k for (k, v) in self.responses.iteritems() if v] def retrieve_response(self, correlation_id): """ Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict with the following keys: method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message Parameters ---------- correlation_id: string Identifier to retrieve the RPC response for """ if correlation_id not in self.responses: raise KeyError( "Given RPC response correlation_id was not registered.") if not self.responses[correlation_id]: return None response = self.responses[correlation_id] del (self.responses[correlation_id]) return response def request_response(self, exchange, routing_key, message, properties=None, correlation_id=None, timeout=6): """ This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following properties are set, along with any custom properties: * correlation_id: a correlation_id is generated using register_response. It is assumed that the responding service will also provide the same id in the response. * reply_to: this is set to the internal RPC queue name, so we can pickup responses. The mandatory bit will be set on the message as a mechanism to detect if the message was delivered to a queue. This is to avoid needlessly waiting on a reply, when the message wasn't delivered in the first place. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . correlation_id: string Custom correlation_id. This identifier is subject to the same semantics and logic as register_response(). timeout: int How many seconds to wait for a reply. If no reply is received, an MessageDeliveryTimeout is raised. Set to False to wait forever. """ if not properties: properties = {} properties['correlation_id'] = self.register_response(correlation_id) properties['reply_to'] = self.rpc_queue_name if not self.publish(exchange, routing_key, message, properties, mandatory=True): self.retrieve_response(properties['correlation_id']) raise MessageNotDelivered("Message was not delivered to a queue") start = int(time.time()) # Newer versions of pika (>v0.10) don't have a force_data_events any more if hasattr(self.channel, "force_data_events"): self.channel.force_data_events(True) while properties['correlation_id'] not in self.retrieve_available_responses(): self.connection.process_data_events() if timeout and (int(time.time()) - start) > timeout: self.retrieve_response(properties['correlation_id']) raise MessageDeliveryTimeout( "No response received from RPC server within specified period") return self.retrieve_response(properties['correlation_id']) def publish(self, exchange, routing_key, message, properties=None, mandatory=False): """ Publish a message to an AMQP exchange. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . mandatory: boolean If set to True, the mandatory bit will be set on the published message. """ return publish_message(self.channel, exchange, routing_key, message, properties, mandatory) def reply(self, original_headers, message, properties=None): """ Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- original_headers: dict The headers of the originating message that caused this reply. message: string Message to reply with properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . """ rpc_reply(self.channel, original_headers, message, properties)
class Rpc(Queue): ''' Attempts to simplify RPC style calls using AMQP exchanges and queues. This works two-fold: * This class will create an Exchange for sending RPC messages. * This class will also create a Queue for handling responses to the RPC messages. Additionally, this class can also create a 'normal' Queue, to avoid having to create a separate instance. All of the above is created using a single AMQP channel. ''' def __init__(self, host, credentials, identifier=None, prefetch_count=1, exchange=None, auto_delete=True, queue=None, binds=None, confirm_delivery=False): ''' Initialize AMQP connection. Parameters ---------- host: tuple Must contain hostname and port to use for connection credentials: tuple Must contain username and password for this connection identifier: string Identifier for this RPC Queue. This parameter determines what the incoming queue will be called. If left as None, an identifier will be generated. prefetch_count: int Set the prefetch_count of all queues defined by this class. exchange: string If set, this RPC queue will also be bound to the given exchange using the identifier as routing key. If not, we will only be implicitly bound to the default exchange auto_delete: boolean Set to True to automatically delete the created RPC queue. queue: dict Create a separate queue based on the given parameters. This is a general purpose AMQP queue, and can be provided a separate callback using consume(). Must contain at least the following keys: queue: string - what queue to use passive: boolean - should we use an existing queue, to try to declare our own Options below are optional when passive = True durable: boolean - should the queue be durable auto_delete: boolean - should we auto delete the queue when we close the connection binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind confirm_delivery: boolean If True, basic.Confirm will be set on the current channel. ''' pass def consume(self, consumer_callback=None, exclusive=False): ''' Initialize consuming of messages from an AMQP RPC queue. Messages will be consumed after start_consuming() is called. An internal callback will be used to handle incoming RPC responses. Only responses that have been registered with register_response() will be kept internally, all other responses will be dropped silently. Responses can be accessed by using get_response(). The internal callback will assume that the incoming RPC responses will have a correlation_id property set in the headers. Additionally, if a general purpose queue was created on construction, the parameters to this function can be used to declare a callback and options for that queue. A ValueError is raised when trying to set a general purpose callback, but no queue was declared during construction. In contrast to the Queue class, the recover parameter is missing from this implementation of consume(). We will always try to requeue old messages. Parameters ---------- consumer_callback: callback Function to call when a message is consumed. The callback function will be called on each delivery, and will receive three parameters: * channel * method_frame * header_frame * body exclusive: boolean Is this consumer supposed to be the exclusive consumer of the given queue? ''' pass def _rpc_response_callback(self, channel, method_frame, header_frame, body): ''' Internal callback used by consume() Parameters ---------- channel: object Channel from which the callback originated method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message ''' pass def register_response(self, correlation_id=None): ''' Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generating correlation_ids. Depending on the underlying system and implementation, this will guarantee that generated values are unique between workers. At least CPython guarantees this behaviour. Parameters ---------- correlation_id: string Identifier under which to expect a RPC callback. If None, a correlation_id will be generated. ''' pass def retrieve_available_responses(self): ''' Retrieve a list of all available responses. Will return a list of correlation_ids. ''' pass def retrieve_response(self, correlation_id): ''' Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict with the following keys: method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message Parameters ---------- correlation_id: string Identifier to retrieve the RPC response for ''' pass def request_response(self, exchange, routing_key, message, properties=None, correlation_id=None, timeout=6): ''' This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following properties are set, along with any custom properties: * correlation_id: a correlation_id is generated using register_response. It is assumed that the responding service will also provide the same id in the response. * reply_to: this is set to the internal RPC queue name, so we can pickup responses. The mandatory bit will be set on the message as a mechanism to detect if the message was delivered to a queue. This is to avoid needlessly waiting on a reply, when the message wasn't delivered in the first place. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . correlation_id: string Custom correlation_id. This identifier is subject to the same semantics and logic as register_response(). timeout: int How many seconds to wait for a reply. If no reply is received, an MessageDeliveryTimeout is raised. Set to False to wait forever. ''' pass def publish(self, exchange, routing_key, message, properties=None, mandatory=False): ''' Publish a message to an AMQP exchange. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . mandatory: boolean If set to True, the mandatory bit will be set on the published message. ''' pass def reply(self, original_headers, message, properties=None): ''' Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- original_headers: dict The headers of the originating message that caused this reply. message: string Message to reply with properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . ''' pass
10
10
31
4
9
18
3
2.09
1
7
2
0
9
5
9
17
291
44
80
19
70
167
70
18
60
6
2
2
26
146,868
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/amqp/exchange.py
chaos.amqp.exchange.Exchange
class Exchange(object): """ Holds a connection to an AMQP exchange, and methods to publish to it. """ def __init__(self, host, credentials, exchange=None, routing_key=None): """ Initialize AMQP connection. Parameters ---------- host: tuple Must contain hostname and port to use for connection credentials: tuple Must contain username and password for this connection exchange: dict Must contain at least the following keys: exchange: string - what exchange to use exchange_type: string - what type of exchange to use ("direct") passive: boolean - should we use an existing exchange, or try to declare our own Options below are optional when passive = True durable: boolean - should the exchange be durable auto_delete: boolean - should we auto delete the exchange when we close the connection routing_key: string what routing_key to use for published messages. If unset, this parameter must be set during publishing """ self.logger = logging.getLogger(__name__) self.logger.debug( "Creating connection to {0}:{1}".format(host[0], host[1])) self.default_routing_key = routing_key self.credentials = pika.PlainCredentials( credentials[0], credentials[1]) self.parameters = pika.ConnectionParameters( host=host[0], port=host[1], credentials=self.credentials) self.connection = pika.BlockingConnection(self.parameters) self.channel = self.connection.channel() if exchange: self.exchange_name = exchange['exchange'] self.logger.debug( "Declaring exchange {0}".format(self.exchange_name)) self.channel.exchange_declare(**exchange) else: self.exchange_name = None def close(self): """ Closes the internal connection. """ self.logger.debug("Closing AMQP connection") self.connection.close() def publish(self, message, properties=None, mandatory=False): """ Publish a message to an AMQP exchange. Parameters ---------- message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . The following options are also available: routing_key: string - what routing_key to use. MUST be set if this was not set during __init__. exchange: string - what exchange to use. MUST be set if this was not set during __init__. mandatory: boolean If set to True, the mandatory bit will be set on the published message. Returns ------- Depending on the mode of the Channel, the return value can signify different things: basic_Confirm is active: True means that the message has been delivered to a queue, False means it hasn't. mandatory bit was set on message: True means that the message has been delivered to a consumer, False means that it has been returned. No special bit or mode has been set: None is returned. """ return publish_message(self.channel, self.exchange_name, self.default_routing_key, message, properties, mandatory)
class Exchange(object): ''' Holds a connection to an AMQP exchange, and methods to publish to it. ''' def __init__(self, host, credentials, exchange=None, routing_key=None): ''' Initialize AMQP connection. Parameters ---------- host: tuple Must contain hostname and port to use for connection credentials: tuple Must contain username and password for this connection exchange: dict Must contain at least the following keys: exchange: string - what exchange to use exchange_type: string - what type of exchange to use ("direct") passive: boolean - should we use an existing exchange, or try to declare our own Options below are optional when passive = True durable: boolean - should the exchange be durable auto_delete: boolean - should we auto delete the exchange when we close the connection routing_key: string what routing_key to use for published messages. If unset, this parameter must be set during publishing ''' pass def close(self): ''' Closes the internal connection. ''' pass def publish(self, message, properties=None, mandatory=False): ''' Publish a message to an AMQP exchange. Parameters ---------- message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . The following options are also available: routing_key: string - what routing_key to use. MUST be set if this was not set during __init__. exchange: string - what exchange to use. MUST be set if this was not set during __init__. mandatory: boolean If set to True, the mandatory bit will be set on the published message. Returns ------- Depending on the mode of the Channel, the return value can signify different things: basic_Confirm is active: True means that the message has been delivered to a queue, False means it hasn't. mandatory bit was set on message: True means that the message has been delivered to a consumer, False means that it has been returned. No special bit or mode has been set: None is returned. ''' pass
4
4
24
2
6
16
1
2.45
1
0
0
0
3
7
3
3
77
8
20
11
16
49
19
11
15
2
1
1
4
146,869
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/db.py
chaos.db.SimpleDb
class SimpleDb(collections.MutableMapping): """ Implements a simple key/value store based on GDBM. Values are stored as JSON strings, to allow for more complex values than GDBM itself can provide. This class implements the full MutableMapping ABC, which means that after using open(), or using with, this class behaves as a dict. All changes will be saved to disk after using close() or ending the with statement. """ def __init__(self, path, mode="c", sync=True): """ Store the given parameters internally and prepare for opening the database later. Arguments --------- path: string Path where to create or open the database mode: string What mode to use when opening the database: - "r" (read-only) - "w" (read-write) - "c" (read-write, create when not exists) - "n" (read-write, always create new file) sync: boolean If set to True, data will be flushed to disk after every change. """ self.path = path self.mode = mode + ("s" if sync else "") self.db = None def _checkopen(self): if self.db == None: raise RuntimeError("SimpleDb was not opened") def open(self): """ Open the GDBM database internally. """ return self.__enter__() def close(self): """ Close the internal GDBM database. """ self.__exit__(None, None, None) def dumpvalue(self, key): """ Retrieves the given key, and returns the raw JSON encoded string. """ self._checkopen() return self.db[key] def __enter__(self): self.db = gdbm.open(self.path, self.mode) return self def __exit__(self, exc_type, exc_value, traceback): self._checkopen() self.db.sync() self.db.close() self.db = None def __getitem__(self, key): self._checkopen() return json.loads(self.db[key]) def __setitem__(self, key, value): self._checkopen() self.db[key] = json.dumps(value) def __delitem__(self, key): self._checkopen() del (self.db[key]) def __iter__(self): self._checkopen() key = self.db.firstkey() while key != None: yield key key = self.db.nextkey(key) if key == None: raise StopIteration() def __len__(self): self._checkopen() return len(self.db)
class SimpleDb(collections.MutableMapping): ''' Implements a simple key/value store based on GDBM. Values are stored as JSON strings, to allow for more complex values than GDBM itself can provide. This class implements the full MutableMapping ABC, which means that after using open(), or using with, this class behaves as a dict. All changes will be saved to disk after using close() or ending the with statement. ''' def __init__(self, path, mode="c", sync=True): ''' Store the given parameters internally and prepare for opening the database later. Arguments --------- path: string Path where to create or open the database mode: string What mode to use when opening the database: - "r" (read-only) - "w" (read-write) - "c" (read-write, create when not exists) - "n" (read-write, always create new file) sync: boolean If set to True, data will be flushed to disk after every change. ''' pass def _checkopen(self): pass def open(self): ''' Open the GDBM database internally. ''' pass def close(self): ''' Close the internal GDBM database. ''' pass def dumpvalue(self, key): ''' Retrieves the given key, and returns the raw JSON encoded string. ''' pass def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass def __getitem__(self, key): pass def __setitem__(self, key, value): pass def __delitem__(self, key): pass def __iter__(self): pass def __len__(self): pass
13
5
6
0
4
2
1
0.72
1
2
0
0
12
3
12
12
90
16
43
17
30
31
43
17
30
3
1
1
16
146,870
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/multiprocessing/workers.py
chaos.multiprocessing.workers.Workers
class Workers(object): """ Container to register and handle multiple Worker processes. """ worker_list = {} def __init__(self): self.logger = logging.getLogger(__name__) def registerWorker(self, name, worker): """ Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register. """ if not isinstance(worker, multiprocessing.Process): self.logger.error( "Process {0} is not actually a Process!".format(name)) raise Exception( "Process {0} is not actually a Process!".format(name)) if name in self.worker_list: self.logger.error("Process {0} already registered!".format(name)) raise Exception("Process {0} already registered!".format(name)) self.worker_list[name] = worker self.logger.debug("Registered worker {0}".format(name)) return worker def getWorkers(self): """ Retrieve a list of names of all registered Workers. """ return self.worker_list.keys() def getWorker(self, name): """ Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) return self.worker_list[name] def unregisterWorker(self, name): """ Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) del self.worker_list[name] self.logger.debug("Unregistered worker {0}".format(name)) def startAll(self): """ Start all registered Workers. """ self.logger.info("Starting all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Starting {0}".format(process.name)) process.start() self.logger.info("Started all workers") def stopAll(self, timeout=10, stop=False): """ Stop all registered Workers. This is method assumes that the Worker has already received a stop message somehow, and simply joins the Process until it dies, as follows: 1. The Worker is retrieved. 2. The Worker is joined, and will wait until the Worker exits. 3. The Worker is unregistered. 4. If $stop = True, the main process is killed. """ self.logger.info("Stopping all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Stopping {0}".format(process.name)) if process.is_alive(): process.join(timeout) if process.is_alive(): self.logger.warning( "Failed to stop {0}, terminating".format(process.name)) process.terminate() self.unregisterWorker(worker) self.logger.info("Stopped all workers") if stop: self.logger.fatal("Comitting suicide") os._exit(0)
class Workers(object): ''' Container to register and handle multiple Worker processes. ''' def __init__(self): pass def registerWorker(self, name, worker): ''' Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register. ''' pass def getWorkers(self): ''' Retrieve a list of names of all registered Workers. ''' pass def getWorkers(self): ''' Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve ''' pass def unregisterWorker(self, name): ''' Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister ''' pass def startAll(self): ''' Start all registered Workers. ''' pass def stopAll(self, timeout=10, stop=False): ''' Stop all registered Workers. This is method assumes that the Worker has already received a stop message somehow, and simply joins the Process until it dies, as follows: 1. The Worker is retrieved. 2. The Worker is joined, and will wait until the Worker exits. 3. The Worker is unregistered. 4. If $stop = True, the main process is killed. ''' pass
8
7
15
2
7
6
2
0.94
1
1
0
0
7
1
7
7
119
24
49
14
41
46
49
14
41
5
1
3
16
146,871
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/threading/scheduler.py
chaos.threading.scheduler.Scheduler
class Scheduler(threading.Thread): """ A single thread that is automatically called with a specific interval. To stop a thread that is in its main loop, set stop to True. """ def __init__(self, delay, action, name, startNow=False, *args, **kwargs): """ Initialize a new Scheduler thread. Parameters ---------- delay: int The delay between consequtive runs of this thread, in seconds. action: function pointer The function to call. name: string Descriptive name of this thread. startNow: boolean When True, this thread will start immediately when run() is called. When False, this thread will start now+interval seconds when run() is called. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. """ self.logger = logging.getLogger(name) super(Scheduler, self).__init__(None, None, name, None, None) self.delay = delay self.main_action = action self.name = name self.main_args = args self.main_kwargs = kwargs self.stop = False now = datetime.datetime.now() if startNow is True: self.lastRun = datetime.datetime.min self.logger.debug("Thread {0} will start immediately".format(name)) else: self.lastRun = now if isinstance(startNow, (int, long)): self.lastRun += datetime.timedelta(seconds=startNow) wait = (self.lastRun - now).seconds + delay self.logger.debug( "Thread {0} will start in {1} seconds".format(name, wait)) def setStartAction(self, action, *args, **kwargs): """ Set a function to call when run() is called, before the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. """ self.init_action = action self.init_args = args self.init_kwargs = kwargs def setStopAction(self, action, *args, **kwargs): """ Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. """ self.stop_action = action self.stop_args = args self.stop_kwargs = kwargs def run(self): """ Calls the defined action every $interval seconds. Optionally calls an action before the main loop, and an action when stopping, if these are defined. Exceptions in the main loop will NOT cause the thread to die. """ self.logger.debug("Thread {0} is entering main loop".format(self.name)) if hasattr(self, "init_action"): self.logger.debug("Thread {0} is calling its init action") self.init_action(*self.init_args, **self.init_kwargs) while not self.stop: self.logger.debug("Delay is {0}".format(self.delay)) if (datetime.datetime.now() - self.lastRun).total_seconds() > self.delay: self.logger.debug("Thread {0} is running".format(self.name)) try: self.main_action(*self.main_args, **self.main_kwargs) except Exception: self.logger.exception( "Thread {0} generated an exception!".format(self.name)) self.lastRun = datetime.datetime.now() self.logger.debug("Thread {0} is done".format(self.name)) time.sleep(1) if hasattr(self, "stop_action"): self.logger.debug("Thread {0} is calling its stop action") self.stop_action(*self.stop_args, **self.stop_kwargs) self.logger.debug("Thread {0} is exiting main loop".format(self.name))
class Scheduler(threading.Thread): ''' A single thread that is automatically called with a specific interval. To stop a thread that is in its main loop, set stop to True. ''' def __init__(self, delay, action, name, startNow=False, *args, **kwargs): ''' Initialize a new Scheduler thread. Parameters ---------- delay: int The delay between consequtive runs of this thread, in seconds. action: function pointer The function to call. name: string Descriptive name of this thread. startNow: boolean When True, this thread will start immediately when run() is called. When False, this thread will start now+interval seconds when run() is called. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. ''' pass def setStartAction(self, action, *args, **kwargs): ''' Set a function to call when run() is called, before the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. ''' pass def setStopAction(self, action, *args, **kwargs): ''' Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. ''' pass def run(self): ''' Calls the defined action every $interval seconds. Optionally calls an action before the main loop, and an action when stopping, if these are defined. Exceptions in the main loop will NOT cause the thread to die. ''' pass
5
5
26
3
12
11
3
1.02
1
5
0
0
4
14
4
29
114
17
48
21
43
49
47
21
42
6
1
3
11
146,872
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/threading/threads.py
chaos.threading.threads.Threads
class Threads(object): """ Container to register and handle multiple Threads. """ thread_list = {} def __init__(self): self.logger = logging.getLogger(__name__) def registerThread(self, name, thread): """ Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register. """ if not isinstance(thread, threading.Thread): self.logger.error( "Thread {0} is not actually a Thread!".format(name)) raise Exception( "Thread {0} is not actually a Thread!".format(name)) if name in self.thread_list: self.logger.error("Thread {0} already registered!".format(name)) raise Exception("Thread {0} already registered!".format(name)) self.thread_list[name] = thread self.logger.debug("Registered thread {0}".format(name)) return thread def getThreads(self): """ Retrieve a list of names of all registered Threads. """ return self.thread_list.keys() def getThread(self, name): """ Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) return self.thread_list[name] def unregisterThread(self, name): """ Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) del self.thread_list[name] self.logger.debug("Unregistered thread {0}".format(name)) def startAll(self): """ Start all registered Threads. """ self.logger.info("Starting all threads...") for thread in self.getThreads(): thr = self.getThread(thread) self.logger.debug("Starting {0}".format(thr.name)) thr.start() self.logger.info("Started all threads") def stopAll(self, stop=False): """ Stop all registered Threads. This is method assumes that the Thread is using and internal variable called stop to control its main loop. Stopping a Thread is achieved as follows: 1. The Thread is retrieved. 2. $thread.stop is set to False. 3. The Thread is joined, and will wait until the Thread exits. 4. The Thread is unregistered. 5. If $exit = True, the main process is killed. Ensure that any registered Thread responds to having its stop property set to False, else calling stopAll() will result in a hung process. """ self.logger.info("Stopping all threads...") for thread in self.getThreads(): thr = self.getThread(thread) self.logger.debug("Stopping {0}".format(thr.name)) thr.stop = True thr.join() self.unregisterThread(thread) self.logger.info("Stopped all threads") if stop: self.logger.fatal("Comitting suicide") os._exit(0)
class Threads(object): ''' Container to register and handle multiple Threads. ''' def __init__(self): pass def registerThread(self, name, thread): ''' Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register. ''' pass def getThreads(self): ''' Retrieve a list of names of all registered Threads. ''' pass def getThreads(self): ''' Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve ''' pass def unregisterThread(self, name): ''' Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister ''' pass def startAll(self): ''' Start all registered Threads. ''' pass def stopAll(self, stop=False): ''' Stop all registered Threads. This is method assumes that the Thread is using and internal variable called stop to control its main loop. Stopping a Thread is achieved as follows: 1. The Thread is retrieved. 2. $thread.stop is set to False. 3. The Thread is joined, and will wait until the Thread exits. 4. The Thread is unregistered. 5. If $exit = True, the main process is killed. Ensure that any registered Thread responds to having its stop property set to False, else calling stopAll() will result in a hung process. ''' pass
8
7
15
3
6
7
2
1.07
1
2
0
0
7
1
7
7
120
25
46
14
38
49
46
14
38
3
1
1
14
146,873
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/cli.py
chaos.cli.SimpleCliTool
class SimpleCliTool(object): envvars = {} def add_env(self, var, value): """ Store a custom environment value internally. This value is used on every call to _call_cli. """ self.envvars[var] = value def del_env(self, var): """ Delete a custom environment value. This will raise an exception if the variable does not exist. """ del (self.envvars[var]) def get_env(self): """ Return the internally stored dict of environment variables. """ return self.envvars def _call_cli(self, command, cwd=None, universal_newlines=False, redirect_stderr=False): """ Executes the given command, internally using Popen. The output of stdout and stderr are returned as a tuple. The returned tuple looks like: (stdout, stderr, returncode) Parameters ---------- command: string The command to execute. cwd: string Change the working directory of the program to the specified path. universal_newlines: boolean Enable the universal_newlines feature of Popen. redirect_stderr: boolean If True, redirect stderr into stdout """ command = str(command.encode("utf-8").decode("ascii", "ignore")) env = os.environ.copy() env.update(self.envvars) stderr = STDOUT if redirect_stderr else PIPE proc = Popen(shlex.split(command), stdout=PIPE, stderr=stderr, cwd=cwd, universal_newlines=universal_newlines, env=env) stdout, stderr = proc.communicate() return (stdout, stderr, proc.returncode)
class SimpleCliTool(object): def add_env(self, var, value): ''' Store a custom environment value internally. This value is used on every call to _call_cli. ''' pass def del_env(self, var): ''' Delete a custom environment value. This will raise an exception if the variable does not exist. ''' pass def get_env(self): ''' Return the internally stored dict of environment variables. ''' pass def _call_cli(self, command, cwd=None, universal_newlines=False, redirect_stderr=False): ''' Executes the given command, internally using Popen. The output of stdout and stderr are returned as a tuple. The returned tuple looks like: (stdout, stderr, returncode) Parameters ---------- command: string The command to execute. cwd: string Change the working directory of the program to the specified path. universal_newlines: boolean Enable the universal_newlines feature of Popen. redirect_stderr: boolean If True, redirect stderr into stdout ''' pass
5
4
11
1
4
7
1
1.63
1
2
0
0
4
0
4
4
48
6
16
10
11
26
16
10
11
2
1
0
5
146,874
LordGaav/python-chaos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LordGaav_python-chaos/chaos/globber.py
chaos.globber.Globber
class Globber(object): """ Traverses a directory and returns all absolute filenames. """ def __init__(self, path, include=None, recursive=True): """ Initialize Globber parameters. Filter may be a list of globbing patterns. Parameters ---------- path: string Absolute path to the directory to glob include: list of strings List of globbing pattern strings. By default, ALL files in the given path are globbed. recursive: boolean When True: will traverse subdirectories found in $path. Defaults to True. """ if include is None: include = ['*'] self.path = path self.include = include self.recursive = recursive def glob(self): """ Traverse directory, and return all absolute filenames of files that match the globbing patterns. """ matches = [] for root, dirnames, filenames in os.walk(self.path): if not self.recursive: while len(dirnames) > 0: dirnames.pop() for include in self.include: for filename in fnmatch.filter(filenames, include): matches.append(os.path.join(root, filename)) return matches
class Globber(object): ''' Traverses a directory and returns all absolute filenames. ''' def __init__(self, path, include=None, recursive=True): ''' Initialize Globber parameters. Filter may be a list of globbing patterns. Parameters ---------- path: string Absolute path to the directory to glob include: list of strings List of globbing pattern strings. By default, ALL files in the given path are globbed. recursive: boolean When True: will traverse subdirectories found in $path. Defaults to True. ''' pass def glob(self): ''' Traverse directory, and return all absolute filenames of files that match the globbing patterns. ''' pass
3
3
17
1
8
8
4
1.12
1
0
0
0
2
3
2
2
39
3
17
10
14
19
17
10
14
6
1
3
8
146,875
LordGaav/python-chaos
LordGaav_python-chaos/chaos/amqp/exceptions.py
chaos.amqp.exceptions.MessageNotDelivered
class MessageNotDelivered(IOError): """ Exception to be raised when an AMQP message could not be queued. """ pass
class MessageNotDelivered(IOError): ''' Exception to be raised when an AMQP message could not be queued. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
0
5
0
2
1
1
3
2
1
1
0
1
0
0
146,876
LordGaav/python-chaos
LordGaav_python-chaos/chaos/amqp/exceptions.py
chaos.amqp.exceptions.MessageDeliveryTimeout
class MessageDeliveryTimeout(IOError): """ Exception to be raised when an AMQP message could not be delivered in the specified period. """ pass
class MessageDeliveryTimeout(IOError): ''' Exception to be raised when an AMQP message could not be delivered in the specified period. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
0
5
0
2
1
1
3
2
1
1
0
1
0
0
146,877
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TAtom
class TAtom(TestCase): def test_no_children(self): fileobj = cBytesIO(b"\x00\x00\x00\x08atom") atom = Atom(fileobj) self.failUnlessRaises(KeyError, atom.__getitem__, "test") def test_length_1(self): fileobj = cBytesIO(b"\x00\x00\x00\x01atom" b"\x00\x00\x00\x00\x00\x00\x00\x10" + b"\x00" * 16) self.failUnlessEqual(Atom(fileobj).length, 16) def test_length_64bit_less_than_16(self): fileobj = cBytesIO(b"\x00\x00\x00\x01atom" b"\x00\x00\x00\x00\x00\x00\x00\x08" + b"\x00" * 8) self.assertRaises(error, Atom, fileobj) def test_length_less_than_8(self): fileobj = cBytesIO(b"\x00\x00\x00\x02atom") self.assertRaises(MP4MetadataError, Atom, fileobj) def test_render_too_big(self): class TooBig(bytes): def __len__(self): return 1 << 32 data = TooBig(b"test") try: len(data) except OverflowError: # Py_ssize_t is still only 32 bits on this system. self.failUnlessRaises(OverflowError, Atom.render, b"data", data) else: data = Atom.render(b"data", data) self.failUnlessEqual(len(data), 4 + 4 + 8 + 4) def test_non_top_level_length_0_is_invalid(self): data = cBytesIO(struct.pack(">I4s", 0, b"whee")) self.assertRaises(MP4MetadataError, Atom, data, level=1) def test_length_0(self): fileobj = cBytesIO(b"\x00\x00\x00\x00atom" + 40 * b"\x00") atom = Atom(fileobj) self.failUnlessEqual(fileobj.tell(), 48) self.failUnlessEqual(atom.length, 48) def test_length_0_container(self): data = cBytesIO(struct.pack(">I4s", 0, b"moov") + Atom.render(b"data", b"whee")) atom = Atom(data) self.failUnlessEqual(len(atom.children), 1) self.failUnlessEqual(atom.length, 20) self.failUnlessEqual(atom.children[-1].length, 12)
class TAtom(TestCase): def test_no_children(self): pass def test_length_1(self): pass def test_length_64bit_less_than_16(self): pass def test_length_less_than_8(self): pass def test_render_too_big(self): pass class TooBig(bytes): def __len__(self): pass def test_non_top_level_length_0_is_invalid(self): pass def test_length_0(self): pass def test_length_0_container(self): pass
11
0
5
0
5
0
1
0.02
1
6
4
0
8
0
8
83
51
8
42
22
31
1
40
22
29
2
3
1
10
146,878
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.RBUF
class RBUF(FrameOpt): """Recommended buffer size. Attributes: * size -- recommended buffer size in bytes * info -- if ID3 tags may be elsewhere in the file (optional) * offset -- the location of the next ID3 tag, if any Mutagen will not find the next tag itself. """ _framespec = [SizedIntegerSpec('size', 3)] _optionalspec = [ ByteSpec('info'), SizedIntegerSpec('offset', 4), ] def __eq__(self, other): return self.size == other __hash__ = FrameOpt.__hash__ def __pos__(self): return self.size
class RBUF(FrameOpt): '''Recommended buffer size. Attributes: * size -- recommended buffer size in bytes * info -- if ID3 tags may be elsewhere in the file (optional) * offset -- the location of the next ID3 tag, if any Mutagen will not find the next tag itself. ''' def __eq__(self, other): pass def __pos__(self): pass
3
1
2
0
2
0
1
0.64
1
0
0
1
2
0
2
19
26
8
11
6
8
7
8
6
5
1
3
0
2
146,879
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4
class TMP4(TestCase): def setUp(self): fd, self.filename = mkstemp(suffix='.m4a') os.close(fd) shutil.copy(self.original, self.filename) self.audio = MP4(self.filename) def faad(self): if not have_faad: return value = os.system("faad %s -o %s > %s 2> %s" % ( self.filename, devnull, devnull, devnull)) self.failIf(value and value != NOTFOUND) def test_score(self): fileobj = open(self.filename, "rb") header = fileobj.read(128) self.failUnless(MP4.score(self.filename, fileobj, header)) fileobj.close() def test_channels(self): self.failUnlessEqual(self.audio.info.channels, 2) def test_sample_rate(self): self.failUnlessEqual(self.audio.info.sample_rate, 44100) def test_bits_per_sample(self): self.failUnlessEqual(self.audio.info.bits_per_sample, 16) def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 2914) def test_length(self): self.failUnlessAlmostEqual(3.7, self.audio.info.length, 1) def test_padding(self): self.audio[b"\xa9nam"] = u"wheeee" * 10 self.audio.save() size1 = os.path.getsize(self.audio.filename) self.audio[b"\xa9nam"] = u"wheeee" * 11 self.audio.save() size2 = os.path.getsize(self.audio.filename) self.failUnless(size1, size2) def test_padding_2(self): self.audio[b"\xa9nam"] = u"wheeee" * 10 self.audio.save() # Reorder "free" and "ilst" atoms fileobj = open(self.audio.filename, "rb+") atoms = Atoms(fileobj) meta = atoms[b"moov", b"udta", b"meta"] meta_length1 = meta.length ilst = meta[b"ilst",] free = meta[b"free",] self.failUnlessEqual(ilst.offset + ilst.length, free.offset) fileobj.seek(ilst.offset) ilst_data = fileobj.read(ilst.length) fileobj.seek(free.offset) free_data = fileobj.read(free.length) fileobj.seek(ilst.offset) fileobj.write(free_data + ilst_data) fileobj.close() fileobj = open(self.audio.filename, "rb+") atoms = Atoms(fileobj) meta = atoms[b"moov", b"udta", b"meta"] ilst = meta[b"ilst",] free = meta[b"free",] self.failUnlessEqual(free.offset + free.length, ilst.offset) fileobj.close() # Save the file self.audio[b"\xa9nam"] = u"wheeee" * 11 self.audio.save() # Check the order of "free" and "ilst" atoms fileobj = open(self.audio.filename, "rb+") atoms = Atoms(fileobj) fileobj.close() meta = atoms[b"moov", b"udta", b"meta"] ilst = meta[b"ilst",] free = meta[b"free",] self.failUnlessEqual(meta.length, meta_length1) self.failUnlessEqual(ilst.offset + ilst.length, free.offset) def set_key(self, key, value, result=None, faad=True): self.audio[key] = value self.audio.save() audio = MP4(self.audio.filename) self.failUnless(key in audio) self.failUnlessEqual(audio[key], result or value) if faad: self.faad() def test_unicode(self): self.set_key(b'\xa9nam', [b'\xe3\x82\x8a\xe3\x81\x8b'], result=[u'\u308a\u304b']) def test_save_text(self): self.set_key(b'\xa9nam', [u"Some test name"]) def test_save_texts(self): self.set_key(b'\xa9nam', [u"Some test name", u"One more name"]) def test_freeform(self): self.set_key(b'----:net.sacredchao.Mutagen:test key', [b"whee"]) def test_freeform_2(self): self.set_key(b'----:net.sacredchao.Mutagen:test key', b"whee", [b"whee"]) def test_freeforms(self): self.set_key(b'----:net.sacredchao.Mutagen:test key', [b"whee", b"uhh"]) def test_freeform_bin(self): self.set_key(b'----:net.sacredchao.Mutagen:test key', [ MP4FreeForm(b'woooo', MP4FreeForm.FORMAT_TEXT), MP4FreeForm(b'hoooo', MP4FreeForm.FORMAT_DATA), MP4FreeForm(b'boooo'), ]) def test_tracknumber(self): self.set_key(b'trkn', [(1, 10)]) self.set_key(b'trkn', [(1, 10), (5, 20)], faad=False) self.set_key(b'trkn', []) def test_disk(self): self.set_key(b'disk', [(18, 0)]) self.set_key(b'disk', [(1, 10), (5, 20)], faad=False) self.set_key(b'disk', []) def test_tracknumber_too_small(self): self.failUnlessRaises(ValueError, self.set_key, b'trkn', [(-1, 0)]) self.failUnlessRaises(ValueError, self.set_key, b'trkn', [(2**18, 1)]) def test_disk_too_small(self): self.failUnlessRaises(ValueError, self.set_key, b'disk', [(-1, 0)]) self.failUnlessRaises(ValueError, self.set_key, b'disk', [(2**18, 1)]) def test_tracknumber_wrong_size(self): self.failUnlessRaises(ValueError, self.set_key, b'trkn', (1,)) self.failUnlessRaises(ValueError, self.set_key, b'trkn', (1, 2, 3,)) self.failUnlessRaises(ValueError, self.set_key, b'trkn', [(1,)]) self.failUnlessRaises(ValueError, self.set_key, b'trkn', [(1, 2, 3,)]) def test_disk_wrong_size(self): self.failUnlessRaises(ValueError, self.set_key, b'disk', [(1,)]) self.failUnlessRaises(ValueError, self.set_key, b'disk', [(1, 2, 3,)]) def test_tempo(self): self.set_key(b'tmpo', [150]) self.set_key(b'tmpo', []) def test_tempos(self): self.set_key(b'tmpo', [160, 200], faad=False) def test_tempo_invalid(self): for badvalue in [[10000000], [-1], 10, "foo"]: self.failUnlessRaises(ValueError, self.set_key, b'tmpo', badvalue) def test_compilation(self): self.set_key(b'cpil', True) def test_compilation_false(self): self.set_key(b'cpil', False) def test_gapless(self): self.set_key(b'pgap', True) def test_gapless_false(self): self.set_key(b'pgap', False) def test_podcast(self): self.set_key(b'pcst', True) def test_podcast_false(self): self.set_key(b'pcst', False) def test_cover(self): self.set_key(b'covr', [b'woooo']) def test_cover_png(self): self.set_key(b'covr', [ MP4Cover(b'woooo', MP4Cover.FORMAT_PNG), MP4Cover(b'hoooo', MP4Cover.FORMAT_JPEG), ]) def test_podcast_url(self): self.set_key(b'purl', ['http://pdl.warnerbros.com/wbie/justiceleagueheroes/audio/JLH_EA.xml']) def test_episode_guid(self): self.set_key(b'catg', ['falling-star-episode-1']) def test_pprint(self): self.failUnless(self.audio.pprint()) def test_pprint_binary(self): self.audio[b"covr"] = [b"\x00\xa9\garbage"] self.failUnless(self.audio.pprint()) def test_pprint_pair(self): self.audio[b"cpil"] = (1, 10) if PY2: self.failUnless("'cpil'=(1, 10)" in self.audio.pprint()) else: self.failUnless("b'cpil'=(1, 10)" in self.audio.pprint()) def test_delete(self): self.audio.delete() audio = MP4(self.audio.filename) self.failIf(audio.tags) self.faad() def test_module_delete(self): delete(self.filename) audio = MP4(self.audio.filename) self.failIf(audio.tags) self.faad() def test_reads_unknown_text(self): self.set_key(b"foob", [u"A test"]) def __read_offsets(self, filename): fileobj = open(filename, 'rb') atoms = Atoms(fileobj) moov = atoms[b'moov'] samples = [] for atom in moov.findall(b'stco', True): fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = ">%dI" % cdata.uint_be(data[:4]) offsets = struct.unpack(fmt, data[4:]) for offset in offsets: fileobj.seek(offset) samples.append(fileobj.read(8)) for atom in moov.findall(b'co64', True): fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = ">%dQ" % cdata.uint_be(data[:4]) offsets = struct.unpack(fmt, data[4:]) for offset in offsets: fileobj.seek(offset) samples.append(fileobj.read(8)) try: for atom in atoms[b"moof"].findall(b'tfhd', True): data = fileobj.read(atom.length - 9) flags = cdata.uint_be(b"\x00" + data[:3]) if flags & 1: offset = cdata.ulonglong_be(data[7:15]) fileobj.seek(offset) samples.append(fileobj.read(8)) except KeyError: pass fileobj.close() return samples def test_update_offsets(self): aa = self.__read_offsets(self.original) self.audio[b"\xa9nam"] = b"wheeeeeeee" self.audio.save() bb = self.__read_offsets(self.filename) for a, b in zip(aa, bb): self.failUnlessEqual(a, b) def test_mime(self): self.failUnless("audio/mp4" in self.audio.mime) def tearDown(self): os.unlink(self.filename)
class TMP4(TestCase): def setUp(self): pass def faad(self): pass def test_score(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_bits_per_sample(self): pass def test_bitrate(self): pass def test_length(self): pass def test_padding(self): pass def test_padding_2(self): pass def set_key(self, key, value, result=None, faad=True): pass def test_unicode(self): pass def test_save_text(self): pass def test_save_texts(self): pass def test_freeform(self): pass def test_freeform_2(self): pass def test_freeforms(self): pass def test_freeform_bin(self): pass def test_tracknumber(self): pass def test_disk(self): pass def test_tracknumber_too_small(self): pass def test_disk_too_small(self): pass def test_tracknumber_wrong_size(self): pass def test_disk_wrong_size(self): pass def test_tempo(self): pass def test_tempos(self): pass def test_tempo_invalid(self): pass def test_compilation(self): pass def test_compilation_false(self): pass def test_gapless(self): pass def test_gapless_false(self): pass def test_podcast(self): pass def test_podcast_false(self): pass def test_cover(self): pass def test_cover_png(self): pass def test_podcast_url(self): pass def test_episode_guid(self): pass def test_pprint(self): pass def test_pprint_binary(self): pass def test_pprint_pair(self): pass def test_delete(self): pass def test_module_delete(self): pass def test_reads_unknown_text(self): pass def __read_offsets(self, filename): pass def test_update_offsets(self): pass def test_mime(self): pass def tearDown(self): pass
48
0
5
0
5
0
1
0.01
1
8
5
4
47
2
47
122
264
46
215
80
167
3
206
80
158
8
3
3
59
146,880
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4CovrWithName
class TMP4CovrWithName(TMP4): # http://bugs.musicbrainz.org/ticket/5894 original = os.path.join("tests", "data", "covr-with-name.m4a") def test_has_covr(self): self.failUnless(b'covr' in self.audio.tags) covr = self.audio.tags[b'covr'] self.failUnlessEqual(len(covr), 2) self.failUnlessEqual(covr[0].imageformat, MP4Cover.FORMAT_PNG) self.failUnlessEqual(covr[1].imageformat, MP4Cover.FORMAT_JPEG)
class TMP4CovrWithName(TMP4): def test_has_covr(self): pass
2
0
6
0
6
0
1
0.13
1
1
1
0
1
0
1
123
10
1
8
4
6
1
8
4
6
1
4
0
1
146,881
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4Datatypes
class TMP4Datatypes(TMP4HasTags): original = os.path.join("tests", "data", "has-tags.m4a") def test_has_freeform(self): key = b"----:com.apple.iTunes:iTunNORM" self.failUnless(key in self.audio.tags) ff = self.audio.tags[key] self.failUnlessEqual(ff[0].dataformat, MP4FreeForm.FORMAT_TEXT) def test_has_covr(self): self.failUnless(b'covr' in self.audio.tags) covr = self.audio.tags[b'covr'] self.failUnlessEqual(len(covr), 2) self.failUnlessEqual(covr[0].imageformat, MP4Cover.FORMAT_PNG) self.failUnlessEqual(covr[1].imageformat, MP4Cover.FORMAT_JPEG)
class TMP4Datatypes(TMP4HasTags): def test_has_freeform(self): pass def test_has_covr(self): pass
3
0
6
0
6
0
1
0
1
2
2
0
2
0
2
129
15
2
13
7
10
0
13
7
10
1
5
0
2
146,882
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4HasTags
class TMP4HasTags(TMP4): def test_save_simple(self): self.audio.save() self.faad() def test_shrink(self): self.audio.clear() self.audio.save() audio = MP4(self.audio.filename) self.failIf(audio.tags) def test_too_short(self): fileobj = open(self.audio.filename, "rb") try: atoms = Atoms(fileobj) ilst = atoms[b"moov.udta.meta.ilst"] # fake a too long atom length ilst.children[0].length += 10000000 self.failUnlessRaises(MP4MetadataError, MP4Tags, atoms, fileobj) finally: fileobj.close() def test_has_tags(self): self.failUnless(self.audio.tags) def test_not_my_file(self): # should raise something like "Not a MP4 file" self.failUnlessRaisesRegexp( error, "MP4", MP4, os.path.join("tests", "data", "empty.ogg"))
class TMP4HasTags(TMP4): def test_save_simple(self): pass def test_shrink(self): pass def test_too_short(self): pass def test_has_tags(self): pass def test_not_my_file(self): pass
6
0
5
0
4
0
1
0.09
1
5
5
2
5
0
5
127
29
4
23
10
17
2
21
10
15
1
4
1
5
146,883
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4HasTags64Bit
class TMP4HasTags64Bit(TMP4HasTags): original = os.path.join("tests", "data", "truncated-64bit.mp4") def test_has_covr(self): pass def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 128000) def test_length(self): self.failUnlessAlmostEqual(0.325, self.audio.info.length, 3) def faad(self): # This is only half a file, so FAAD segfaults. Can't test. :( pass
class TMP4HasTags64Bit(TMP4HasTags): def test_has_covr(self): pass def test_bitrate(self): pass def test_length(self): pass def faad(self): pass
5
0
2
0
2
0
1
0.1
1
0
0
0
4
0
4
131
15
4
10
6
5
1
10
6
5
1
5
0
4
146,884
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4Info
class TMP4Info(TestCase): def test_no_soun(self): self.failUnlessRaises( IOError, self.test_mdhd_version_1, b"vide") def test_mdhd_version_1(self, soun=b"soun"): mdhd = Atom.render(b"mdhd", (b"\x01\x00\x00\x00" + b"\x00" * 16 + b"\x00\x00\x00\x02" + # 2 Hz b"\x00\x00\x00\x00\x00\x00\x00\x10")) hdlr = Atom.render(b"hdlr", b"\x00" * 8 + soun) mdia = Atom.render(b"mdia", mdhd + hdlr) trak = Atom.render(b"trak", mdia) moov = Atom.render(b"moov", trak) fileobj = cBytesIO(moov) atoms = Atoms(fileobj) info = MP4Info(atoms, fileobj) self.failUnlessEqual(info.length, 8) def test_multiple_tracks(self): hdlr = Atom.render(b"hdlr", b"\x00" * 8 + b"whee") mdia = Atom.render(b"mdia", hdlr) trak1 = Atom.render(b"trak", mdia) mdhd = Atom.render(b"mdhd", (b"\x01\x00\x00\x00" + b"\x00" * 16 + b"\x00\x00\x00\x02" + # 2 Hz b"\x00\x00\x00\x00\x00\x00\x00\x10")) hdlr = Atom.render(b"hdlr", b"\x00" * 8 + b"soun") mdia = Atom.render(b"mdia", mdhd + hdlr) trak2 = Atom.render(b"trak", mdia) moov = Atom.render(b"moov", trak1 + trak2) fileobj = cBytesIO(moov) atoms = Atoms(fileobj) info = MP4Info(atoms, fileobj) self.failUnlessEqual(info.length, 8)
class TMP4Info(TestCase): def test_no_soun(self): pass def test_mdhd_version_1(self, soun=b"soun"): pass def test_multiple_tracks(self): pass
4
0
10
0
10
1
1
0.06
1
3
3
0
3
0
3
78
34
3
31
21
27
2
26
21
22
1
3
0
3
146,885
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4NoTags3G2
class TMP4NoTags3G2(TMP4): original = os.path.join("tests", "data", "no-tags.3g2") def test_no_tags(self): self.failUnless(self.audio.tags is None) def test_sample_rate(self): self.failUnlessEqual(self.audio.info.sample_rate, 22050) def test_bitrate(self): self.failUnlessEqual(self.audio.info.bitrate, 32000) def test_length(self): self.failUnlessAlmostEqual(15, self.audio.info.length, 1)
class TMP4NoTags3G2(TMP4): def test_no_tags(self): pass def test_sample_rate(self): pass def test_bitrate(self): pass def test_length(self): pass
5
0
2
0
2
0
1
0
1
0
0
0
4
0
4
126
14
4
10
6
5
0
10
6
5
1
4
0
4
146,886
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4NoTagsM4A
class TMP4NoTagsM4A(TMP4): original = os.path.join("tests", "data", "no-tags.m4a") def test_no_tags(self): self.failUnless(self.audio.tags is None) def test_add_tags(self): self.audio.add_tags() self.failUnlessRaises(error, self.audio.add_tags)
class TMP4NoTagsM4A(TMP4): def test_no_tags(self): pass def test_add_tags(self): pass
3
0
3
0
3
0
1
0
1
1
1
0
2
0
2
124
9
2
7
4
4
0
7
4
4
1
4
0
2
146,887
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4Tags
class TMP4Tags(TestCase): def wrap_ilst(self, data): ilst = Atom.render(b"ilst", data) meta = Atom.render(b"meta", b"\x00" * 4 + ilst) data = Atom.render(b"moov", Atom.render(b"udta", meta)) fileobj = cBytesIO(data) return MP4Tags(Atoms(fileobj), fileobj) def test_genre(self): data = Atom.render(b"data", b"\x00" * 8 + b"\x00\x01") genre = Atom.render(b"gnre", data) tags = self.wrap_ilst(genre) self.failIf(b"gnre" in tags) self.failUnlessEqual(tags[b"\xa9gen"], ["Blues"]) def test_empty_cpil(self): cpil = Atom.render(b"cpil", Atom.render(b"data", b"\x00" * 8)) tags = self.wrap_ilst(cpil) self.failUnless(b"cpil" in tags) self.failIf(tags[b"cpil"]) def test_genre_too_big(self): data = Atom.render(b"data", b"\x00" * 8 + b"\x01\x00") genre = Atom.render(b"gnre", data) tags = self.wrap_ilst(genre) self.failIf(b"gnre" in tags) self.failIf(b"\xa9gen" in tags) def test_strips_unknown_types(self): data = Atom.render(b"data", b"\x00" * 8 + b"whee") foob = Atom.render(b"foob", data) tags = self.wrap_ilst(foob) self.failIf(tags) def test_strips_bad_unknown_types(self): data = Atom.render(b"datA", b"\x00" * 8 + b"whee") foob = Atom.render(b"foob", data) tags = self.wrap_ilst(foob) self.failIf(tags) def test_bad_covr(self): data = Atom.render(b"foob", b"\x00\x00\x00\x0E" + b"\x00" * 4 + b"whee") covr = Atom.render(b"covr", data) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, covr) def test_covr_blank_format(self): data = Atom.render(b"data", b"\x00\x00\x00\x00" + b"\x00" * 4 + b"whee") covr = Atom.render(b"covr", data) tags = self.wrap_ilst(covr) self.failUnlessEqual(MP4Cover.FORMAT_JPEG, tags[b"covr"][0].imageformat) def test_render_bool(self): self.failUnlessEqual(MP4Tags()._MP4Tags__render_bool(b'pgap', True), b"\x00\x00\x00\x19pgap\x00\x00\x00\x11data" b"\x00\x00\x00\x15\x00\x00\x00\x00\x01") self.failUnlessEqual(MP4Tags()._MP4Tags__render_bool(b'pgap', False), b"\x00\x00\x00\x19pgap\x00\x00\x00\x11data" b"\x00\x00\x00\x15\x00\x00\x00\x00\x00") def test_render_text(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_text(b'purl', ['http://foo/bar.xml'], 0), b"\x00\x00\x00*purl\x00\x00\x00\"data\x00\x00\x00\x00\x00\x00" b"\x00\x00http://foo/bar.xml") self.failUnlessEqual( MP4Tags()._MP4Tags__render_text(b'aART', [u'\u0041lbum Artist']), b"\x00\x00\x00$aART\x00\x00\x00\x1cdata\x00\x00\x00\x01\x00\x00" b"\x00\x00\x41lbum Artist") self.failUnlessEqual( MP4Tags()._MP4Tags__render_text(b'aART', [u'Album Artist', u'Whee']), b"\x00\x00\x008aART\x00\x00\x00\x1cdata\x00\x00\x00\x01\x00\x00" b"\x00\x00Album Artist\x00\x00\x00\x14data\x00\x00\x00\x01\x00" b"\x00\x00\x00Whee") def test_render_data(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_data(b'aART', 1, [b'whee']), b"\x00\x00\x00\x1caART" b"\x00\x00\x00\x14data\x00\x00\x00\x01\x00\x00\x00\x00whee") self.failUnlessEqual( MP4Tags()._MP4Tags__render_data(b'aART', 2, [b'whee', b'wee']), b"\x00\x00\x00/aART" b"\x00\x00\x00\x14data\x00\x00\x00\x02\x00\x00\x00\x00whee" b"\x00\x00\x00\x13data\x00\x00\x00\x02\x00\x00\x00\x00wee") def test_bad_text_data(self): data = Atom.render(b"datA", b"\x00\x00\x00\x01\x00\x00\x00\x00whee") data = Atom.render(b"aART", data) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, data) def test_render_freeform(self): self.failUnlessEqual( MP4Tags()._MP4Tags__render_freeform( b'----:net.sacredchao.Mutagen:test', [b'whee', b'wee']), b"\x00\x00\x00a----" b"\x00\x00\x00\"mean\x00\x00\x00\x00net.sacredchao.Mutagen" b"\x00\x00\x00\x10name\x00\x00\x00\x00test" b"\x00\x00\x00\x14data\x00\x00\x00\x01\x00\x00\x00\x00whee" b"\x00\x00\x00\x13data\x00\x00\x00\x01\x00\x00\x00\x00wee") def test_bad_freeform(self): mean = Atom.render(b"mean", b"net.sacredchao.Mutagen") name = Atom.render(b"name", b"empty test key") bad_freeform = Atom.render(b"----", b"\x00" * 4 + mean + name) self.failUnlessRaises(MP4MetadataError, self.wrap_ilst, bad_freeform) def test_pprint_non_text_list(self): tags = MP4Tags() tags[b"tmpo"] = [120, 121] tags[b"trck"] = [(1, 2), (3, 4)] tags.pprint() def test_freeform_data(self): # http://code.google.com/p/mutagen/issues/detail?id=103 key = b"----:com.apple.iTunes:Encoding Params" value = (b"vers\x00\x00\x00\x01acbf\x00\x00\x00\x01brat\x00\x01\xf4" b"\x00cdcv\x00\x01\x05\x04") data = (b"\x00\x00\x00\x1cmean\x00\x00\x00\x00com.apple.iTunes\x00\x00" b"\x00\x1bname\x00\x00\x00\x00Encoding Params\x00\x00\x000data" b"\x00\x00\x00\x00\x00\x00\x00\x00vers\x00\x00\x00\x01acbf\x00" b"\x00\x00\x01brat\x00\x01\xf4\x00cdcv\x00\x01\x05\x04") tags = self.wrap_ilst(Atom.render(b"----", data)) v = tags[key][0] self.failUnlessEqual(v, value) self.failUnlessEqual(v.dataformat, MP4FreeForm.FORMAT_DATA) data = MP4Tags()._MP4Tags__render_freeform(key, v) v = self.wrap_ilst(data)[key][0] self.failUnlessEqual(v.dataformat, MP4FreeForm.FORMAT_DATA) data = MP4Tags()._MP4Tags__render_freeform(key, value) v = self.wrap_ilst(data)[key][0] self.failUnlessEqual(v.dataformat, MP4FreeForm.FORMAT_TEXT)
class TMP4Tags(TestCase): def wrap_ilst(self, data): pass def test_genre(self): pass def test_empty_cpil(self): pass def test_genre_too_big(self): pass def test_strips_unknown_types(self): pass def test_strips_bad_unknown_types(self): pass def test_bad_covr(self): pass def test_covr_blank_format(self): pass def test_render_bool(self): pass def test_render_text(self): pass def test_render_data(self): pass def test_bad_text_data(self): pass def test_render_freeform(self): pass def test_bad_freeform(self): pass def test_pprint_non_text_list(self): pass def test_freeform_data(self): pass
17
0
7
0
7
0
1
0.01
1
6
6
0
16
0
16
91
136
20
115
49
98
1
83
49
66
1
3
0
16
146,888
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp3.py
tests.test_mp3.TMPEGInfo
class TMPEGInfo(TestCase): def test_not_real_file(self): filename = os.path.join("tests", "data", "silence-44-s-v1.mp3") fileobj = cBytesIO(open(filename, "rb").read(20)) MPEGInfo(fileobj) def test_empty(self): fileobj = cBytesIO(b"") self.failUnlessRaises(IOError, MPEGInfo, fileobj)
class TMPEGInfo(TestCase): def test_not_real_file(self): pass def test_empty(self): pass
3
0
4
0
4
0
1
0
1
1
1
0
2
0
2
77
10
2
8
6
5
0
8
6
5
1
3
0
2
146,889
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp4.py
tests.test_mp4.TMP4UpdateParents64Bit
class TMP4UpdateParents64Bit(TestCase): original = os.path.join("tests", "data", "64bit.mp4") def setUp(self): fd, self.filename = mkstemp(suffix='.mp4') os.close(fd) shutil.copy(self.original, self.filename) def test_update_parents(self): with open(self.filename, "rb") as fileobj: atoms = Atoms(fileobj) self.assertEqual(77, atoms.atoms[0].length) self.assertEqual(61, atoms.atoms[0].children[0].length) tags = MP4Tags(atoms, fileobj) tags[b'pgap'] = True tags.save(self.filename) with open(self.filename, "rb") as fileobj: atoms = Atoms(fileobj) # original size + 'pgap' size + padding self.assertEqual(77 + 25 + 974, atoms.atoms[0].length) self.assertEqual(61 + 25 + 974, atoms.atoms[0].children[0].length) def tearDown(self): os.unlink(self.filename)
class TMP4UpdateParents64Bit(TestCase): def setUp(self): pass def test_update_parents(self): pass def tearDown(self): pass
4
0
7
0
6
0
1
0.05
1
2
2
0
3
1
3
78
25
4
20
9
16
1
20
8
16
1
3
1
3
146,890
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_musepack.py
tests.test_musepack.TMusepackWithID3
class TMusepackWithID3(TestCase): SAMPLE = os.path.join("tests", "data", "click.mpc") def setUp(self): fd, self.NEW = mkstemp(suffix='mpc') os.close(fd) shutil.copy(self.SAMPLE, self.NEW) with open(self.SAMPLE, "rb") as h1: with open(self.NEW, "rb") as h2: self.failUnlessEqual(h1.read(), h2.read()) def tearDown(self): os.unlink(self.NEW) def test_ignore_id3(self): id3 = ID3() id3.add(TIT2(encoding=0, text='id3 title')) id3.save(self.NEW) f = Musepack(self.NEW) f['title'] = 'apev2 title' f.save() id3 = ID3(self.NEW) self.failUnlessEqual(id3['TIT2'], 'id3 title') f = Musepack(self.NEW) self.failUnlessEqual(f['title'], 'apev2 title')
class TMusepackWithID3(TestCase): def setUp(self): pass def tearDown(self): pass def test_ignore_id3(self): pass
4
0
7
0
7
0
1
0
1
3
3
0
3
1
3
78
25
3
22
10
18
0
22
8
18
1
3
2
3
146,891
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_ogg.py
tests.test_ogg.TOggFileType
class TOggFileType(TestCase): def scan_file(self): fileobj = open(self.filename, "rb") try: try: while True: OggPage(fileobj) except EOFError: pass finally: fileobj.close() def test_pprint_empty(self): self.audio.pprint() def test_pprint_stuff(self): self.test_set_two_tags() self.audio.pprint() def test_length(self): self.failUnlessAlmostEqual(3.7, self.audio.info.length, 1) def test_no_tags(self): self.failIf(self.audio.tags) self.failIf(self.audio.tags is None) def test_vendor_safe(self): self.audio["vendor"] = "a vendor" self.audio.save() audio = self.Kind(self.filename) self.failUnlessEqual(audio["vendor"], ["a vendor"]) def test_set_two_tags(self): self.audio["foo"] = ["a"] self.audio["bar"] = ["b"] self.audio.save() audio = self.Kind(self.filename) self.failUnlessEqual(len(audio.tags.keys()), 2) self.failUnlessEqual(audio["foo"], ["a"]) self.failUnlessEqual(audio["bar"], ["b"]) self.scan_file() def test_save_twice(self): self.audio.save() self.audio.save() self.failUnlessEqual(self.Kind(self.filename).tags, self.audio.tags) self.scan_file() def test_set_delete(self): self.test_set_two_tags() self.audio.tags.clear() self.audio.save() audio = self.Kind(self.filename) self.failIf(audio.tags) self.scan_file() def test_delete(self): self.test_set_two_tags() self.audio.delete() self.failIf(self.audio.tags) audio = self.Kind(self.filename) self.failIf(audio.tags) self.audio["foobar"] = "foobar" * 1000 self.audio.save() audio = self.Kind(self.filename) self.failUnlessEqual(self.audio["foobar"], audio["foobar"]) self.scan_file() def test_really_big(self): self.audio["foo"] = "foo" * (2**16) self.audio["bar"] = "bar" * (2**16) self.audio["baz"] = "quux" * (2**16) self.audio.save() audio = self.Kind(self.filename) self.failUnlessEqual(audio["foo"], ["foo" * 2**16]) self.failUnlessEqual(audio["bar"], ["bar" * 2**16]) self.failUnlessEqual(audio["baz"], ["quux" * 2**16]) self.scan_file() def test_delete_really_big(self): self.audio["foo"] = "foo" * (2**16) self.audio["bar"] = "bar" * (2**16) self.audio["baz"] = "quux" * (2**16) self.audio.save() self.audio.delete() audio = self.Kind(self.filename) self.failIf(audio.tags) self.scan_file() def test_invalid_open(self): self.failUnlessRaises(IOError, self.Kind, os.path.join('tests', 'data', 'xing.mp3')) def test_invalid_delete(self): self.failUnlessRaises(IOError, self.audio.delete, os.path.join('tests', 'data', 'xing.mp3')) def test_invalid_save(self): self.failUnlessRaises(IOError, self.audio.save, os.path.join('tests', 'data', 'xing.mp3')) def ogg_reference(self, filename): self.scan_file() if have_ogginfo: value = os.system("ogginfo %s > %s 2> %s" % (filename, devnull, devnull)) self.failIf(value and value != NOTFOUND, "ogginfo failed on %s" % filename) if have_oggz_validate: if filename.endswith(".opus") and not have_oggz_validate_opus: return value = os.system( "oggz-validate %s > %s" % (filename, devnull)) self.failIf(value and value != NOTFOUND, "oggz-validate failed on %s" % filename) def test_ogg_reference_simple_save(self): self.audio.save() self.ogg_reference(self.filename) def test_ogg_reference_really_big(self): self.test_really_big() self.audio.save() self.ogg_reference(self.filename) def test_ogg_reference_delete(self): self.audio.delete() self.ogg_reference(self.filename) def test_ogg_reference_medium_sized(self): self.audio["foobar"] = "foobar" * 1000 self.audio.save() self.ogg_reference(self.filename) def test_ogg_reference_delete_readd(self): self.audio.delete() self.audio.tags.clear() self.audio["foobar"] = "foobar" * 1000 self.audio.save() self.ogg_reference(self.filename) def test_mime_secondary(self): self.failUnless('application/ogg' in self.audio.mime) def tearDown(self): os.unlink(self.filename)
class TOggFileType(TestCase): def scan_file(self): pass def test_pprint_empty(self): pass def test_pprint_stuff(self): pass def test_length(self): pass def test_no_tags(self): pass def test_vendor_safe(self): pass def test_set_two_tags(self): pass def test_save_twice(self): pass def test_set_delete(self): pass def test_delete(self): pass def test_really_big(self): pass def test_delete_really_big(self): pass def test_invalid_open(self): pass def test_invalid_delete(self): pass def test_invalid_save(self): pass def ogg_reference(self, filename): pass def test_ogg_reference_simple_save(self): pass def test_ogg_reference_really_big(self): pass def test_ogg_reference_delete(self): pass def test_ogg_reference_medium_sized(self): pass def test_ogg_reference_delete_readd(self): pass def test_mime_secondary(self): pass def tearDown(self): pass
24
0
5
0
5
0
1
0
1
2
1
5
23
0
23
98
149
25
124
32
100
0
116
32
92
4
3
3
28
146,892
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_ogg.py
tests.test_ogg.TOggPage
class TOggPage(TestCase): def setUp(self): self.fileobj = open(os.path.join("tests", "data", "empty.ogg"), "rb") self.page = OggPage(self.fileobj) pages = [OggPage(), OggPage(), OggPage()] pages[0].packets = [b"foo"] pages[1].packets = [b"bar"] pages[2].packets = [b"baz"] for i in range(len(pages)): pages[i].sequence = i for page in pages: page.serial = 1 self.pages = pages def test_flags(self): self.failUnless(self.page.first) self.failIf(self.page.continued) self.failIf(self.page.last) self.failUnless(self.page.complete) for first in [True, False]: self.page.first = first for last in [True, False]: self.page.last = last for continued in [True, False]: self.page.continued = continued self.failUnlessEqual(self.page.first, first) self.failUnlessEqual(self.page.last, last) self.failUnlessEqual(self.page.continued, continued) def test_flags_next_page(self): page = OggPage(self.fileobj) self.failIf(page.first) self.failIf(page.continued) self.failIf(page.last) def test_length(self): # Always true for Ogg Vorbis files self.failUnlessEqual(self.page.size, 58) self.failUnlessEqual(len(self.page.write()), 58) def test_first_metadata_page_is_separate(self): self.failIf(OggPage(self.fileobj).continued) def test_single_page_roundtrip(self): self.failUnlessEqual( self.page, OggPage(BytesIO(self.page.write()))) def test_at_least_one_audio_page(self): page = OggPage(self.fileobj) while not page.last: page = OggPage(self.fileobj) self.failUnless(page.last) def test_crappy_fragmentation(self): packets = [b"1" * 511, b"2" * 511, b"3" * 511] pages = OggPage.from_packets(packets, default_size=510, wiggle_room=0) self.failUnless(len(pages) > 3) self.failUnlessEqual(OggPage.to_packets(pages), packets) def test_wiggle_room(self): packets = [b"1" * 511, b"2" * 511, b"3" * 511] pages = OggPage.from_packets(packets, default_size=510, wiggle_room=100) self.failUnlessEqual(len(pages), 3) self.failUnlessEqual(OggPage.to_packets(pages), packets) def test_one_packet_per_wiggle(self): packets = [b"1" * 511, b"2" * 511, b"3" * 511] pages = OggPage.from_packets( packets, default_size=1000, wiggle_room=1000000) self.failUnlessEqual(len(pages), 2) self.failUnlessEqual(OggPage.to_packets(pages), packets) def test_renumber(self): self.failUnlessEqual( [page.sequence for page in self.pages], [0, 1, 2]) fileobj = BytesIO() for page in self.pages: fileobj.write(page.write()) fileobj.seek(0) OggPage.renumber(fileobj, 1, 10) fileobj.seek(0) pages = [OggPage(fileobj) for i in range(3)] self.failUnlessEqual([page.sequence for page in pages], [10, 11, 12]) fileobj.seek(0) OggPage.renumber(fileobj, 1, 20) fileobj.seek(0) pages = [OggPage(fileobj) for i in range(3)] self.failUnlessEqual([page.sequence for page in pages], [20, 21, 22]) def test_renumber_extradata(self): fileobj = BytesIO() for page in self.pages: fileobj.write(page.write()) fileobj.write(b"left over data") fileobj.seek(0) # Trying to rewrite should raise an error... self.failUnlessRaises(Exception, OggPage.renumber, fileobj, 1, 10) fileobj.seek(0) # But the already written data should remain valid, pages = [OggPage(fileobj) for i in range(3)] self.failUnlessEqual([page.sequence for page in pages], [10, 11, 12]) # And the garbage that caused the error should be okay too. self.failUnlessEqual(fileobj.read(), b"left over data") def test_renumber_reread(self): try: fd, filename = mkstemp(suffix=".ogg") os.close(fd) shutil.copy(os.path.join("tests", "data", "multipagecomment.ogg"), filename) fileobj = open(filename, "rb+") OggPage.renumber(fileobj, 1002429366, 20) fileobj.close() fileobj = open(filename, "rb+") OggPage.renumber(fileobj, 1002429366, 0) fileobj.close() finally: try: os.unlink(filename) except OSError: pass def test_renumber_muxed(self): pages = [OggPage() for i in range(10)] for seq, page in enumerate(pages[0:1] + pages[2:]): page.serial = 0 page.sequence = seq pages[1].serial = 2 pages[1].sequence = 100 data = BytesIO(b"".join([page.write() for page in pages])) OggPage.renumber(data, 0, 20) data.seek(0) pages = [OggPage(data) for i in range(10)] self.failUnlessEqual(pages[1].serial, 2) self.failUnlessEqual(pages[1].sequence, 100) pages.pop(1) self.failUnlessEqual( [page.sequence for page in pages], list(range(20, 29))) def test_to_packets(self): self.failUnlessEqual( [b"foo", b"bar", b"baz"], OggPage.to_packets(self.pages)) self.pages[0].complete = False self.pages[1].continued = True self.failUnlessEqual( [b"foobar", b"baz"], OggPage.to_packets(self.pages)) def test_to_packets_mixed_stream(self): self.pages[0].serial = 3 self.failUnlessRaises(ValueError, OggPage.to_packets, self.pages) def test_to_packets_missing_sequence(self): self.pages[0].sequence = 3 self.failUnlessRaises(ValueError, OggPage.to_packets, self.pages) def test_to_packets_continued(self): self.pages[0].continued = True self.failUnlessEqual( OggPage.to_packets(self.pages), [b"foo", b"bar", b"baz"]) def test_to_packets_continued_strict(self): self.pages[0].continued = True self.failUnlessRaises( ValueError, OggPage.to_packets, self.pages, strict=True) def test_to_packets_strict(self): for page in self.pages: page.complete = False self.failUnlessRaises( ValueError, OggPage.to_packets, self.pages, strict=True) def test_from_packets_short_enough(self): packets = [b"1" * 200, b"2" * 200, b"3" * 200] pages = OggPage.from_packets(packets) self.failUnlessEqual(OggPage.to_packets(pages), packets) def test_from_packets_position(self): packets = [b"1" * 100000] pages = OggPage.from_packets(packets) self.failUnless(len(pages) > 1) for page in pages[:-1]: self.failUnlessEqual(-1, page.position) self.failUnlessEqual(0, pages[-1].position) def test_from_packets_long(self): packets = [b"1" * 100000, b"2" * 100000, b"3" * 100000] pages = OggPage.from_packets(packets) self.failIf(pages[0].complete) self.failUnless(pages[1].continued) self.failUnlessEqual(OggPage.to_packets(pages), packets) def test_random_data_roundtrip(self): try: random_file = open("/dev/urandom", "rb") except (IOError, OSError): print("WARNING: Random data round trip test disabled.") return for i in range(10): num_packets = random.randrange(2, 100) lengths = [random.randrange(10, 10000) for i in range(num_packets)] packets = list(map(random_file.read, lengths)) self.failUnlessEqual( packets, OggPage.to_packets(OggPage.from_packets(packets))) def test_packet_exactly_255(self): page = OggPage() page.packets = [b"1" * 255] page.complete = False page2 = OggPage() page2.packets = [b""] page2.sequence = 1 page2.continued = True self.failUnlessEqual( [b"1" * 255], OggPage.to_packets([page, page2])) def test_page_max_size_alone_too_big(self): page = OggPage() page.packets = [b"1" * 255 * 255] page.complete = True self.failUnlessRaises(ValueError, page.write) def test_page_max_size(self): page = OggPage() page.packets = [b"1" * 255 * 255] page.complete = False page2 = OggPage() page2.packets = [b""] page2.sequence = 1 page2.continued = True self.failUnlessEqual( [b"1" * 255 * 255], OggPage.to_packets([page, page2])) def test_complete_zero_length(self): packets = [b""] * 20 page = OggPage.from_packets(packets)[0] new_page = OggPage(BytesIO(page.write())) self.failUnlessEqual(new_page, page) self.failUnlessEqual(OggPage.to_packets([new_page]), packets) def test_too_many_packets(self): packets = [b"1"] * 3000 pages = OggPage.from_packets(packets) for p in pages: OggPage.write(p) self.failUnless(len(pages) > 3000//255) def test_read_max_size(self): page = OggPage() page.packets = [b"1" * 255 * 255] page.complete = False page2 = OggPage() page2.packets = [b"", b"foo"] page2.sequence = 1 page2.continued = True data = page.write() + page2.write() fileobj = BytesIO(data) self.failUnlessEqual(OggPage(fileobj), page) self.failUnlessEqual(OggPage(fileobj), page2) self.failUnlessRaises(EOFError, OggPage, fileobj) def test_invalid_version(self): page = OggPage() OggPage(BytesIO(page.write())) page.version = 1 self.failUnlessRaises(OggError, OggPage, BytesIO(page.write())) def test_not_enough_lacing(self): data = OggPage().write()[:-1] + b"\x10" self.failUnlessRaises(OggError, OggPage, BytesIO(data)) def test_not_enough_data(self): data = OggPage().write()[:-1] + b"\x01\x10" self.failUnlessRaises(OggError, OggPage, BytesIO(data)) def test_not_equal(self): self.failIfEqual(OggPage(), 12) def test_find_last(self): pages = [OggPage() for i in range(10)] for i, page in enumerate(pages): page.sequence = i data = BytesIO(b"".join([page.write() for page in pages])) self.failUnlessEqual( OggPage.find_last(data, pages[0].serial), pages[-1]) def test_find_last_really_last(self): pages = [OggPage() for i in range(10)] pages[-1].last = True for i, page in enumerate(pages): page.sequence = i data = BytesIO(b"".join([page.write() for page in pages])) self.failUnlessEqual( OggPage.find_last(data, pages[0].serial), pages[-1]) def test_find_last_muxed(self): pages = [OggPage() for i in range(10)] for i, page in enumerate(pages): page.sequence = i pages[-2].last = True pages[-1].serial = pages[0].serial + 1 data = BytesIO(b"".join([page.write() for page in pages])) self.failUnlessEqual( OggPage.find_last(data, pages[0].serial), pages[-2]) def test_find_last_no_serial(self): pages = [OggPage() for i in range(10)] for i, page in enumerate(pages): page.sequence = i data = BytesIO(b"".join([page.write() for page in pages])) self.failUnless(OggPage.find_last(data, pages[0].serial + 1) is None) def test_find_last_invalid(self): data = BytesIO(b"if you think this is an Ogg, you're crazy") self.failUnlessRaises(OggError, OggPage.find_last, data, 0) # Disabled because GStreamer will write Oggs with bad data, # which we need to make a best guess for. # #def test_find_last_invalid_sync(self): # data = BytesIO("if you think this is an OggS, you're crazy") # self.failUnlessRaises(OggError, OggPage.find_last, data, 0) def test_find_last_invalid_sync(self): data = BytesIO(b"if you think this is an OggS, you're crazy") page = OggPage.find_last(data, 0) self.failIf(page) def test_crc_py25(self): # Make sure page.write can handle both signed/unsigned int # return values of crc32. # http://code.google.com/p/mutagen/issues/detail?id=63 # http://docs.python.org/library/zlib.html#zlib.crc32 import zlib old_crc = zlib.crc32 def zlib_uint(*args): return (old_crc(*args) & 0xffffffff) def zlib_int(*args): return cdata.int_be(cdata.to_uint_be(old_crc(*args) & 0xffffffff)) try: page = OggPage() page.packets = [b"abc"] zlib.crc32 = zlib_uint uint_data = page.write() zlib.crc32 = zlib_int int_data = page.write() finally: zlib.crc32 = old_crc self.failUnlessEqual(uint_data, int_data) def tearDown(self): self.fileobj.close()
class TOggPage(TestCase): def setUp(self): pass def test_flags(self): pass def test_flags_next_page(self): pass def test_length(self): pass def test_first_metadata_page_is_separate(self): pass def test_single_page_roundtrip(self): pass def test_at_least_one_audio_page(self): pass def test_crappy_fragmentation(self): pass def test_wiggle_room(self): pass def test_one_packet_per_wiggle(self): pass def test_renumber(self): pass def test_renumber_extradata(self): pass def test_renumber_reread(self): pass def test_renumber_muxed(self): pass def test_to_packets(self): pass def test_to_packets_mixed_stream(self): pass def test_to_packets_missing_sequence(self): pass def test_to_packets_continued(self): pass def test_to_packets_continued_strict(self): pass def test_to_packets_strict(self): pass def test_from_packets_short_enough(self): pass def test_from_packets_position(self): pass def test_from_packets_long(self): pass def test_random_data_roundtrip(self): pass def test_packet_exactly_255(self): pass def test_page_max_size_alone_too_big(self): pass def test_page_max_size_alone_too_big(self): pass def test_complete_zero_length(self): pass def test_too_many_packets(self): pass def test_read_max_size(self): pass def test_invalid_version(self): pass def test_not_enough_lacing(self): pass def test_not_enough_data(self): pass def test_not_equal(self): pass def test_find_last(self): pass def test_find_last_really_last(self): pass def test_find_last_muxed(self): pass def test_find_last_no_serial(self): pass def test_find_last_invalid(self): pass def test_find_last_invalid_sync(self): pass def test_crc_py25(self): pass def zlib_uint(*args): pass def zlib_int(*args): pass def tearDown(self): pass
45
0
7
0
7
0
1
0.05
1
10
2
0
42
3
42
117
354
51
289
123
243
14
277
123
231
4
3
3
63
146,893
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_oggflac.py
tests.test_oggflac.TOggFLAC
class TOggFLAC(TOggFileType): Kind = OggFLAC def setUp(self): original = os.path.join("tests", "data", "empty.oggflac") fd, self.filename = mkstemp(suffix='.ogg') os.close(fd) shutil.copy(original, self.filename) self.audio = OggFLAC(self.filename) def test_vendor(self): self.failUnless( self.audio.tags.vendor.startswith("reference libFLAC")) self.failUnlessRaises(KeyError, self.audio.tags.__getitem__, "vendor") def test_streaminfo_bad_marker(self): page = OggPage(open(self.filename, "rb")).write() page = page.replace(b"fLaC", b"!fLa", 1) self.failUnlessRaises(IOError, OggFLACStreamInfo, cBytesIO(page)) def test_streaminfo_too_short(self): page = OggPage(open(self.filename, "rb")).write() self.failUnlessRaises(OggError, OggFLACStreamInfo, cBytesIO(page[:10])) def test_streaminfo_bad_version(self): page = OggPage(open(self.filename, "rb")).write() page = page.replace(b"\x01\x00", b"\x02\x00", 1) self.failUnlessRaises(IOError, OggFLACStreamInfo, cBytesIO(page)) def test_flac_reference_simple_save(self): if not have_flac: return self.audio.save() self.scan_file() value = os.system("flac --ogg -t %s 2> %s" % (self.filename, devnull)) self.failIf(value and value != NOTFOUND) def test_flac_reference_really_big(self): if not have_flac: return self.test_really_big() self.audio.save() self.scan_file() value = os.system("flac --ogg -t %s 2> %s" % (self.filename, devnull)) self.failIf(value and value != NOTFOUND) def test_module_delete(self): delete(self.filename) self.scan_file() self.failIf(OggFLAC(self.filename).tags) def test_flac_reference_delete(self): if not have_flac: return self.audio.delete() self.scan_file() value = os.system("flac --ogg -t %s 2> %s" % (self.filename, devnull)) self.failIf(value and value != NOTFOUND) def test_flac_reference_medium_sized(self): if not have_flac: return self.audio["foobar"] = "foobar" * 1000 self.audio.save() self.scan_file() value = os.system("flac --ogg -t %s 2> %s" % (self.filename, devnull)) self.failIf(value and value != NOTFOUND) def test_flac_reference_delete_readd(self): if not have_flac: return self.audio.delete() self.audio.tags.clear() self.audio["foobar"] = "foobar" * 1000 self.audio.save() self.scan_file() value = os.system("flac --ogg -t %s 2> %s" % (self.filename, devnull)) self.failIf(value and value != NOTFOUND) def test_not_my_ogg(self): fn = os.path.join('tests', 'data', 'empty.ogg') self.failUnlessRaises(IOError, type(self.audio), fn) self.failUnlessRaises(IOError, self.audio.save, fn) self.failUnlessRaises(IOError, self.audio.delete, fn) def test_mime(self): self.failUnless("audio/x-oggflac" in self.audio.mime)
class TOggFLAC(TOggFileType): def setUp(self): pass def test_vendor(self): pass def test_streaminfo_bad_marker(self): pass def test_streaminfo_too_short(self): pass def test_streaminfo_bad_version(self): pass def test_flac_reference_simple_save(self): pass def test_flac_reference_really_big(self): pass def test_module_delete(self): pass def test_flac_reference_delete(self): pass def test_flac_reference_medium_sized(self): pass def test_flac_reference_delete_readd(self): pass def test_not_my_ogg(self): pass def test_mime(self): pass
14
0
5
0
5
0
1
0
1
5
3
0
13
2
13
111
82
13
69
27
55
0
73
27
59
2
4
1
18
146,894
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_oggopus.py
tests.test_oggopus.TOggOpus
class TOggOpus(TOggFileType): Kind = OggOpus def setUp(self): original = os.path.join("tests", "data", "example.opus") fd, self.filename = mkstemp(suffix='.opus') os.close(fd) shutil.copy(original, self.filename) self.audio = self.Kind(self.filename) def test_length(self): self.failUnlessAlmostEqual(self.audio.info.length, 11.35, 2) def test_misc(self): self.failUnlessEqual(self.audio.info.channels, 1) self.failUnless(self.audio.tags.vendor.startswith("libopus")) def test_module_delete(self): delete(self.filename) self.scan_file() self.failIf(self.Kind(self.filename).tags) def test_mime(self): self.failUnless("audio/ogg" in self.audio.mime) self.failUnless("audio/ogg; codecs=opus" in self.audio.mime) def test_invalid_not_first(self): page = OggPage(open(self.filename, "rb")) page.first = False self.failUnlessRaises(IOError, OggOpusInfo, BytesIO(page.write())) def test_unsupported_version(self): page = OggPage(open(self.filename, "rb")) data = bytearray(page.packets[0]) data[8] = 0x03 page.packets[0] = bytes(data) OggOpusInfo(BytesIO(page.write())) data[8] = 0x10 page.packets[0] = bytes(data) self.failUnlessRaises(IOError, OggOpusInfo, BytesIO(page.write()))
class TOggOpus(TOggFileType): def setUp(self): pass def test_length(self): pass def test_misc(self): pass def test_module_delete(self): pass def test_mime(self): pass def test_invalid_not_first(self): pass def test_unsupported_version(self): pass
8
0
5
0
4
0
1
0
1
4
2
0
7
2
7
105
42
9
33
15
25
0
33
15
25
1
4
0
7
146,895
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_oggspeex.py
tests.test_oggspeex.TOggSpeex
class TOggSpeex(TOggFileType): Kind = OggSpeex def setUp(self): original = os.path.join("tests", "data", "empty.spx") fd, self.filename = mkstemp(suffix='.ogg') os.close(fd) shutil.copy(original, self.filename) self.audio = self.Kind(self.filename) def test_module_delete(self): delete(self.filename) self.scan_file() self.failIf(OggSpeex(self.filename).tags) def test_channels(self): self.failUnlessEqual(2, self.audio.info.channels) def test_sample_rate(self): self.failUnlessEqual(44100, self.audio.info.sample_rate) def test_bitrate(self): self.failUnlessEqual(0, self.audio.info.bitrate) def test_invalid_not_first(self): page = OggPage(open(self.filename, "rb")) page.first = False self.failUnlessRaises(IOError, OggSpeexInfo, cBytesIO(page.write())) def test_vendor(self): self.failUnless( self.audio.tags.vendor.startswith("Encoded with Speex 1.1.12")) self.failUnlessRaises(KeyError, self.audio.tags.__getitem__, "vendor") def test_not_my_ogg(self): fn = os.path.join('tests', 'data', 'empty.oggflac') self.failUnlessRaises(IOError, type(self.audio), fn) self.failUnlessRaises(IOError, self.audio.save, fn) self.failUnlessRaises(IOError, self.audio.delete, fn) def test_multiplexed_in_headers(self): shutil.copy( os.path.join("tests", "data", "multiplexed.spx"), self.filename) audio = self.Kind(self.filename) audio.tags["foo"] = ["bar"] audio.save() audio = self.Kind(self.filename) self.failUnlessEqual(audio.tags["foo"], ["bar"]) def test_mime(self): self.failUnless("audio/x-speex" in self.audio.mime)
class TOggSpeex(TOggFileType): def setUp(self): pass def test_module_delete(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_bitrate(self): pass def test_invalid_not_first(self): pass def test_vendor(self): pass def test_not_my_ogg(self): pass def test_multiplexed_in_headers(self): pass def test_mime(self): pass
11
0
4
0
4
0
1
0
1
5
3
0
10
2
10
108
51
10
41
18
30
0
39
18
28
1
4
0
10
146,896
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_oggtheora.py
tests.test_oggtheora.TOggTheora
class TOggTheora(TOggFileType): Kind = OggTheora def setUp(self): original = os.path.join("tests", "data", "sample.oggtheora") fd, self.filename = mkstemp(suffix='.ogg') os.close(fd) shutil.copy(original, self.filename) self.audio = OggTheora(self.filename) self.audio2 = OggTheora( os.path.join("tests", "data", "sample_length.oggtheora")) self.audio3 = OggTheora( os.path.join("tests", "data", "sample_bitrate.oggtheora")) def test_theora_bad_version(self): page = OggPage(open(self.filename, "rb")) packet = page.packets[0] packet = packet[:7] + b"\x03\x00" + packet[9:] page.packets = [packet] fileobj = cBytesIO(page.write()) self.failUnlessRaises(IOError, OggTheoraInfo, fileobj) def test_theora_not_first_page(self): page = OggPage(open(self.filename, "rb")) page.first = False fileobj = cBytesIO(page.write()) self.failUnlessRaises(IOError, OggTheoraInfo, fileobj) def test_vendor(self): self.failUnless( self.audio.tags.vendor.startswith("Xiph.Org libTheora")) self.failUnlessRaises(KeyError, self.audio.tags.__getitem__, "vendor") def test_not_my_ogg(self): fn = os.path.join('tests', 'data', 'empty.ogg') self.failUnlessRaises(IOError, type(self.audio), fn) self.failUnlessRaises(IOError, self.audio.save, fn) self.failUnlessRaises(IOError, self.audio.delete, fn) def test_length(self): self.failUnlessAlmostEqual(5.5, self.audio.info.length, 1) self.failUnlessAlmostEqual(0.75, self.audio2.info.length, 2) def test_bitrate(self): self.failUnlessEqual(16777215, self.audio3.info.bitrate) def test_module_delete(self): delete(self.filename) self.scan_file() self.failIf(OggTheora(self.filename).tags) def test_mime(self): self.failUnless("video/x-theora" in self.audio.mime)
class TOggTheora(TOggFileType): def setUp(self): pass def test_theora_bad_version(self): pass def test_theora_not_first_page(self): pass def test_vendor(self): pass def test_not_my_ogg(self): pass def test_length(self): pass def test_bitrate(self): pass def test_module_delete(self): pass def test_mime(self): pass
10
0
5
0
5
0
1
0
1
5
3
0
9
4
9
107
53
9
44
22
34
0
41
22
31
1
4
0
9
146,897
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_oggvorbis.py
tests.test_oggvorbis.TOggVorbis
class TOggVorbis(TOggFileType): Kind = OggVorbis def setUp(self): original = os.path.join("tests", "data", "empty.ogg") fd, self.filename = mkstemp(suffix='.ogg') os.close(fd) shutil.copy(original, self.filename) self.audio = self.Kind(self.filename) def test_module_delete(self): delete(self.filename) self.scan_file() self.failIf(OggVorbis(self.filename).tags) def test_bitrate(self): self.failUnlessEqual(112000, self.audio.info.bitrate) def test_channels(self): self.failUnlessEqual(2, self.audio.info.channels) def test_sample_rate(self): self.failUnlessEqual(44100, self.audio.info.sample_rate) def test_invalid_not_first(self): page = OggPage(open(self.filename, "rb")) page.first = False self.failUnlessRaises(IOError, OggVorbisInfo, cBytesIO(page.write())) def test_avg_bitrate(self): page = OggPage(open(self.filename, "rb")) packet = page.packets[0] packet = (packet[:16] + b"\x00\x00\x01\x00" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + packet[28:]) page.packets[0] = packet info = OggVorbisInfo(cBytesIO(page.write())) self.failUnlessEqual(info.bitrate, 32768) def test_overestimated_bitrate(self): page = OggPage(open(self.filename, "rb")) packet = page.packets[0] packet = (packet[:16] + b"\x00\x00\x01\x00" + b"\x00\x00\x00\x01" + b"\x00\x00\x00\x00" + packet[28:]) page.packets[0] = packet info = OggVorbisInfo(cBytesIO(page.write())) self.failUnlessEqual(info.bitrate, 65536) def test_underestimated_bitrate(self): page = OggPage(open(self.filename, "rb")) packet = page.packets[0] packet = (packet[:16] + b"\x00\x00\x01\x00" + b"\x01\x00\x00\x00" + b"\x00\x00\x01\x00" + packet[28:]) page.packets[0] = packet info = OggVorbisInfo(cBytesIO(page.write())) self.failUnlessEqual(info.bitrate, 65536) def test_negative_bitrate(self): page = OggPage(open(self.filename, "rb")) packet = page.packets[0] packet = (packet[:16] + b"\xff\xff\xff\xff" + b"\xff\xff\xff\xff" + b"\xff\xff\xff\xff" + packet[28:]) page.packets[0] = packet info = OggVorbisInfo(cBytesIO(page.write())) self.failUnlessEqual(info.bitrate, 0) def test_vendor(self): self.failUnless( self.audio.tags.vendor.startswith("Xiph.Org libVorbis")) self.failUnlessRaises(KeyError, self.audio.tags.__getitem__, "vendor") def test_vorbiscomment(self): self.audio.save() self.scan_file() if ogg is None: return self.failUnless(ogg.vorbis.VorbisFile(self.filename)) def test_vorbiscomment_big(self): self.test_really_big() self.audio.save() self.scan_file() if ogg is None: return vfc = ogg.vorbis.VorbisFile(self.filename).comment() self.failUnlessEqual(self.audio["foo"], vfc["foo"]) def test_vorbiscomment_delete(self): self.audio.delete() self.scan_file() if ogg is None: return vfc = ogg.vorbis.VorbisFile(self.filename).comment() self.failUnlessEqual(vfc.keys(), ["VENDOR"]) def test_vorbiscomment_delete_readd(self): self.audio.delete() self.audio.tags.clear() self.audio["foobar"] = "foobar" * 1000 self.audio.save() self.scan_file() if ogg is None: return vfc = ogg.vorbis.VorbisFile(self.filename).comment() self.failUnlessEqual(self.audio["foobar"], vfc["foobar"]) self.failUnless("FOOBAR" in vfc.keys()) self.failUnless("VENDOR" in vfc.keys()) def test_huge_tag(self): vorbis = self.Kind( os.path.join("tests", "data", "multipagecomment.ogg")) self.failUnless("big" in vorbis.tags) self.failUnless("bigger" in vorbis.tags) self.failUnlessEqual(vorbis.tags["big"], ["foobar" * 10000]) self.failUnlessEqual(vorbis.tags["bigger"], ["quuxbaz" * 10000]) self.scan_file() def test_not_my_ogg(self): fn = os.path.join('tests', 'data', 'empty.oggflac') self.failUnlessRaises(IOError, type(self.audio), fn) self.failUnlessRaises(IOError, self.audio.save, fn) self.failUnlessRaises(IOError, self.audio.delete, fn) def test_save_split_setup_packet(self): fn = os.path.join("tests", "data", "multipage-setup.ogg") shutil.copy(fn, self.filename) audio = OggVorbis(self.filename) tags = audio.tags self.failUnless(tags) audio.save() self.audio = OggVorbis(self.filename) self.failUnlessEqual(self.audio.tags, tags) def test_save_split_setup_packet_reference(self): if ogg is None: return self.test_save_split_setup_packet() vfc = ogg.vorbis.VorbisFile(self.filename).comment() for key in self.audio: self.failUnlessEqual(vfc[key], self.audio[key]) self.ogg_reference(self.filename) def test_save_grown_split_setup_packet_reference(self): if ogg is None: return fn = os.path.join("tests", "data", "multipage-setup.ogg") shutil.copy(fn, self.filename) audio = OggVorbis(self.filename) audio["foobar"] = ["quux" * 50000] tags = audio.tags self.failUnless(tags) audio.save() self.audio = OggVorbis(self.filename) self.failUnlessEqual(self.audio.tags, tags) vfc = ogg.vorbis.VorbisFile(self.filename).comment() for key in self.audio: self.failUnlessEqual(vfc[key], self.audio[key]) self.ogg_reference(self.filename) def test_mime(self): self.failUnless("audio/vorbis" in self.audio.mime)
class TOggVorbis(TOggFileType): def setUp(self): pass def test_module_delete(self): pass def test_bitrate(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_invalid_not_first(self): pass def test_avg_bitrate(self): pass def test_overestimated_bitrate(self): pass def test_underestimated_bitrate(self): pass def test_negative_bitrate(self): pass def test_vendor(self): pass def test_vorbiscomment(self): pass def test_vorbiscomment_big(self): pass def test_vorbiscomment_delete(self): pass def test_vorbiscomment_delete_readd(self): pass def test_huge_tag(self): pass def test_not_my_ogg(self): pass def test_save_split_setup_packet(self): pass def test_save_split_setup_packet_reference(self): pass def test_save_grown_split_setup_packet_reference(self): pass def test_mime(self): pass
22
0
6
0
6
0
1
0
1
5
3
0
21
2
21
119
154
21
133
54
111
0
133
54
111
3
4
1
29
146,898
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_optimfrog.py
tests.test_optimfrog.TOptimFROG
class TOptimFROG(TestCase): def setUp(self): self.ofr = OptimFROG(os.path.join("tests", "data", "empty.ofr")) self.ofs = OptimFROG(os.path.join("tests", "data", "empty.ofs")) def test_channels(self): self.failUnlessEqual(self.ofr.info.channels, 2) self.failUnlessEqual(self.ofs.info.channels, 2) def test_sample_rate(self): self.failUnlessEqual(self.ofr.info.sample_rate, 44100) self.failUnlessEqual(self.ofs.info.sample_rate, 44100) def test_length(self): self.failUnlessAlmostEqual(self.ofr.info.length, 3.68, 2) self.failUnlessAlmostEqual(self.ofs.info.length, 3.68, 2) def test_not_my_file(self): self.failUnlessRaises( OptimFROGHeaderError, OptimFROG, os.path.join("tests", "data", "empty.ogg")) self.failUnlessRaises( OptimFROGHeaderError, OptimFROG, os.path.join("tests", "data", "click.mpc")) def test_pprint(self): self.failUnless(self.ofr.pprint()) self.failUnless(self.ofs.pprint())
class TOptimFROG(TestCase): def setUp(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_length(self): pass def test_not_my_file(self): pass def test_pprint(self): pass
7
0
4
0
4
0
1
0
1
2
2
0
6
2
6
81
29
6
23
9
16
0
19
9
12
1
3
0
6
146,899
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_tools.py
tests.test_tools._TTools
class _TTools(TestCase): TOOL_NAME = None def setUp(self): self._main = get_var(self.TOOL_NAME) def get_var(self, name): return get_var(self.TOOL_NAME, name) def call(self, *args): for arg in args: assert isinstance(arg, (str, bytes)) old_stdout = sys.stdout try: out = StringIO() sys.stdout = out try: ret = self._main([self.TOOL_NAME] + list(args)) except SystemExit as e: ret = e.code ret = ret or 0 return (ret, out.getvalue()) finally: sys.stdout = old_stdout def tearDown(self): del self._main
class _TTools(TestCase): def setUp(self): pass def get_var(self, name): pass def call(self, *args): pass def tearDown(self): pass
5
0
5
0
5
0
2
0
1
4
0
5
4
1
4
79
27
4
23
12
18
0
22
11
17
3
3
2
6
146,900
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_tools_mid3iconv.py
tests.test_tools_mid3iconv.TMid3Iconv
class TMid3Iconv(_TTools): TOOL_NAME = "mid3iconv" def setUp(self): super(TMid3Iconv, self).setUp() original = os.path.join('tests', 'data', 'silence-44-s.mp3') fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(original, self.filename) def tearDown(self): super(TMid3Iconv, self).tearDown() os.unlink(self.filename) def test_noop(self): res, out = self.call() self.failIf(res) self.failUnless("Usage:" in out) def test_debug(self): res, out = self.call("-d", "-p", self.filename) self.failIf(res) self.failUnless("TCON=Silence" in out) def test_quiet(self): res, out = self.call("-q", self.filename) self.failIf(res) self.failIf(out) def test_test_data(self): results = set() for codec in CODECS: results.add(AMBIGUOUS.decode(codec)) self.failUnlessEqual(len(results), len(CODECS)) def test_conv_basic(self): from mutagen.id3 import TALB for codec in CODECS: f = ID3(self.filename) f.add(TALB(text=[AMBIGUOUS.decode("latin-1")], encoding=0)) f.save() res, out = self.call("-d", "-e", codec, self.filename) f = ID3(self.filename) self.failUnlessEqual(f["TALB"].encoding, 1) self.failUnlessEqual(f["TALB"].text[0] , AMBIGUOUS.decode(codec)) def test_comm(self): from mutagen.id3 import COMM for codec in CODECS: f = ID3(self.filename) frame = COMM(desc="", lang="eng", encoding=0, text=[AMBIGUOUS.decode("latin-1")]) f.add(frame) f.save() res, out = self.call("-d", "-e", codec, self.filename) f = ID3(self.filename) new_frame = f[frame.HashKey] self.failUnlessEqual(new_frame.encoding, 1) self.failUnlessEqual(new_frame.text[0] , AMBIGUOUS.decode(codec)) def test_remove_v1(self): from mutagen.id3 import ParseID3v1 res, out = self.call("--remove-v1", self.filename) with open(self.filename, "rb") as h: h.seek(-128, 2) data = h.read() self.failUnlessEqual(len(data), 128) self.failIf(ParseID3v1(data))
class TMid3Iconv(_TTools): def setUp(self): pass def tearDown(self): pass def test_noop(self): pass def test_debug(self): pass def test_quiet(self): pass def test_test_data(self): pass def test_conv_basic(self): pass def test_comm(self): pass def test_remove_v1(self): pass
10
0
7
0
6
0
1
0
1
5
3
0
9
1
9
88
72
13
59
32
46
0
58
31
45
2
4
1
12
146,901
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_tools_mid3v2.py
tests.test_tools_mid3v2.TMid3v2
class TMid3v2(_TTools): TOOL_NAME = 'mid3v2' def setUp(self): super(TMid3v2, self).setUp() original = os.path.join('tests', 'data', 'silence-44-s.mp3') fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(original, self.filename) def tearDown(self): super(TMid3v2, self).tearDown() os.unlink(self.filename) def test_list_genres(self): for arg in ["-L", "--list-genres"]: res, out = self.call(arg) self.failUnlessEqual(res, 0) self.failUnless("Acid Punk" in out) def test_list_frames(self): for arg in ["-f", "--list-frames"]: res, out = self.call(arg) self.failUnlessEqual(res, 0) self.failUnless("--APIC" in out) self.failUnless("--TIT2" in out) def test_list(self): f = ID3(self.filename) album = f["TALB"].text[0] for arg in ["-l", "--list"]: res, out = self.call(arg, self.filename) self.failUnlessEqual(res, 0) self.failUnless("TALB=" + album in out) def test_list_raw(self): f = ID3(self.filename) res, out = self.call("--list-raw", self.filename) self.failUnlessEqual(res, 0) self.failUnless(repr(f["TALB"]) in out) def _test_text_frame(self, short, longer, frame): new_value = "TEST" for arg in [short, longer]: orig = ID3(self.filename) frame_class = mutagen.id3.Frames[frame] orig[frame] = frame_class(text=[u"BLAH"], encoding=3) orig.save() res, out = self.call(arg, new_value, self.filename) self.failUnlessEqual(res, 0) self.failIf(out) self.failUnlessEqual(ID3(self.filename)[frame].text, [new_value]) def test_artist(self): self._test_text_frame("-a", "--artist", "TPE1") def test_album(self): self._test_text_frame("-A", "--album", "TALB") def test_title(self): self._test_text_frame("-t", "--song", "TIT2") def test_genre(self): self._test_text_frame("-g", "--genre", "TCON") def test_convert(self): res, out = self.call("--convert", self.filename) self.failUnlessEqual((res, out), (0, "")) def test_split_escape(self): split_escape = self.get_var("split_escape") inout = [ (("", ":"), [""]), ((":", ":"), ["", ""]), ((":", ":", 0), [":"]), ((":b:c:", ":", 0), [":b:c:"]), ((":b:c:", ":", 1), ["", "b:c:"]), ((":b:c:", ":", 2), ["", "b", "c:"]), ((":b:c:", ":", 3), ["", "b", "c", ""]), (("a\\:b:c", ":"), ["a:b", "c"]), (("a\\\\:b:c", ":"), ["a\\", "b", "c"]), (("a\\\\\\:b:c\\:", ":"), ["a\\:b", "c:"]), (("\\", ":"), [""]), (("\\\\", ":"), ["\\"]), (("\\\\a\\b", ":"), ["\\a\\b"]), ] for inargs, out in inout: self.assertEqual(split_escape(*inargs), out) def test_unescape(self): unescape_string = self.get_var("unescape_string") self.assertEqual(unescape_string("\\n"), "\n") def test_artist_escape(self): res, out = self.call("-e", "-a", "foo\\nbar", self.filename) self.failUnlessEqual(res, 0) self.failIf(out) f = ID3(self.filename) self.failUnlessEqual(f["TPE1"][0], "foo\nbar") def test_txxx_escape(self): res, out = self.call( "-e", "--TXXX", "EscapeTest\\:\\:albumartist:Ex\\:ample", self.filename) self.failUnlessEqual(res, 0) self.failIf(out) f = ID3(self.filename) frame = f.getall("TXXX")[0] self.failUnlessEqual(frame.desc, "EscapeTest::albumartist") self.failUnlessEqual(frame.text, ["Ex:ample"]) def test_txxx(self): res, out = self.call("--TXXX", "A\\:B:C", self.filename) self.failUnlessEqual((res, out), (0, "")) f = ID3(self.filename) frame = f.getall("TXXX")[0] self.failUnlessEqual(frame.desc, "A\\") self.failUnlessEqual(frame.text, ["B:C"]) def test_comm1(self): res, out = self.call("--COMM", "A", self.filename) self.failUnlessEqual((res, out), (0, "")) f = ID3(self.filename) frame = f.getall("COMM:")[0] self.failUnlessEqual(frame.desc, "") self.failUnlessEqual(frame.text, ["A"]) def test_comm2(self): res, out = self.call("--COMM", "Y:B", self.filename) self.failUnlessEqual((res, out), (0, "")) f = ID3(self.filename) frame = f.getall("COMM:Y")[0] self.failUnlessEqual(frame.desc, "Y") self.failUnlessEqual(frame.text, ["B"]) def test_comm2_escape(self): res, out = self.call("-e", "--COMM", "Y\\:B\\nG", self.filename) self.failUnlessEqual((res, out), (0, "")) f = ID3(self.filename) frame = f.getall("COMM:")[0] self.failUnlessEqual(frame.desc, "") self.failUnlessEqual(frame.text, ["Y:B\nG"]) def test_comm3(self): res, out = self.call("--COMM", "Z:B:C:D:ger", self.filename) self.failUnlessEqual((res, out), (0, "")) f = ID3(self.filename) frame = f.getall("COMM:Z")[0] self.failUnlessEqual(frame.desc, "Z") self.failUnlessEqual(frame.text, ["B:C:D"]) self.failUnlessEqual(frame.lang, "ger") #def test_encoding_with_escape(self): # import locale # text = u'\xe4\xf6\xfc' # enc = locale.getpreferredencoding() # # don't fail in case getpreferredencoding doesn't give us a unicode # # encoding. # text = text.encode(enc, errors="replace") # res, out = self.call("-e", "-a", text, self.filename) # self.failUnlessEqual((res, out), (0, "")) # f = ID3(self.filename) # self.assertEqual(f.getall("TPE1")[0], text.decode(enc)) if PY2: def test_invalid_encoding(self): res, out = self.call("--TALB", b'\\xff', '-e', self.filename) self.failIfEqual(res, 0) self.failUnless("TALB" in out) def test_invalid_escape(self): res, out = self.call("--TALB", b'\\xaz', '-e', self.filename) self.failIfEqual(res, 0) self.failUnless("TALB" in out) res, out = self.call("--TALB", b'\\', '-e', self.filename) self.failIfEqual(res, 0) self.failUnless("TALB" in out)
class TMid3v2(_TTools): def setUp(self): pass def tearDown(self): pass def test_list_genres(self): pass def test_list_frames(self): pass def test_list_genres(self): pass def test_list_raw(self): pass def _test_text_frame(self, short, longer, frame): pass def test_artist(self): pass def test_album(self): pass def test_title(self): pass def test_genre(self): pass def test_convert(self): pass def test_split_escape(self): pass def test_unescape(self): pass def test_artist_escape(self): pass def test_txxx_escape(self): pass def test_txxx_escape(self): pass def test_comm1(self): pass def test_comm2(self): pass def test_comm2_escape(self): pass def test_comm3(self): pass def test_invalid_encoding(self): pass def test_invalid_escape(self): pass
24
0
6
0
6
0
1
0.08
1
2
1
0
23
1
23
102
188
35
142
69
118
11
126
69
102
2
4
1
28
146,902
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_musepack.py
tests.test_musepack.TMusepack
class TMusepack(TestCase): def setUp(self): self.sv8 = Musepack(os.path.join("tests", "data", "sv8_header.mpc")) self.sv7 = Musepack(os.path.join("tests", "data", "click.mpc")) self.sv5 = Musepack(os.path.join("tests", "data", "sv5_header.mpc")) self.sv4 = Musepack(os.path.join("tests", "data", "sv4_header.mpc")) def test_bad_header(self): self.failUnlessRaises( MusepackHeaderError, Musepack, os.path.join("tests", "data", "almostempty.mpc")) def test_channels(self): self.failUnlessEqual(self.sv8.info.channels, 2) self.failUnlessEqual(self.sv7.info.channels, 2) self.failUnlessEqual(self.sv5.info.channels, 2) self.failUnlessEqual(self.sv4.info.channels, 2) def test_sample_rate(self): self.failUnlessEqual(self.sv8.info.sample_rate, 44100) self.failUnlessEqual(self.sv7.info.sample_rate, 44100) self.failUnlessEqual(self.sv5.info.sample_rate, 44100) self.failUnlessEqual(self.sv4.info.sample_rate, 44100) def test_bitrate(self): self.failUnlessEqual(self.sv8.info.bitrate, 609) self.failUnlessEqual(self.sv7.info.bitrate, 194530) self.failUnlessEqual(self.sv5.info.bitrate, 39) self.failUnlessEqual(self.sv4.info.bitrate, 39) def test_length(self): self.failUnlessAlmostEqual(self.sv8.info.length, 1.49, 1) self.failUnlessAlmostEqual(self.sv7.info.length, 0.07, 2) self.failUnlessAlmostEqual(self.sv5.info.length, 26.3, 1) self.failUnlessAlmostEqual(self.sv4.info.length, 26.3, 1) def test_gain(self): self.failUnlessAlmostEqual(self.sv8.info.title_gain, -4.668, 3) self.failUnlessAlmostEqual(self.sv8.info.title_peak, 0.5288, 3) self.failUnlessEqual(self.sv8.info.title_gain, self.sv8.info.album_gain) self.failUnlessEqual(self.sv8.info.title_peak, self.sv8.info.album_peak) self.failUnlessAlmostEqual(self.sv7.info.title_gain, 9.27, 6) self.failUnlessAlmostEqual(self.sv7.info.title_peak, 0.1149, 4) self.failUnlessEqual(self.sv7.info.title_gain, self.sv7.info.album_gain) self.failUnlessEqual(self.sv7.info.title_peak, self.sv7.info.album_peak) self.failUnlessRaises(AttributeError, getattr, self.sv5, 'title_gain') def test_not_my_file(self): self.failUnlessRaises( MusepackHeaderError, Musepack, os.path.join("tests", "data", "empty.ogg")) self.failUnlessRaises( MusepackHeaderError, Musepack, os.path.join("tests", "data", "emptyfile.mp3")) def test_almost_my_file(self): self.failUnlessRaises( MusepackHeaderError, MusepackInfo, cBytesIO(b"MP+" + b"\x00" * 32)) self.failUnlessRaises( MusepackHeaderError, MusepackInfo, cBytesIO(b"MP+" + b"\x00" * 100)) self.failUnlessRaises( MusepackHeaderError, MusepackInfo, cBytesIO(b"MPCK" + b"\x00" * 100)) def test_pprint(self): self.sv8.pprint() self.sv7.pprint() self.sv5.pprint() self.sv4.pprint() def test_mime(self): self.failUnless("audio/x-musepack" in self.sv7.mime)
class TMusepack(TestCase): def setUp(self): pass def test_bad_header(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_bitrate(self): pass def test_length(self): pass def test_gain(self): pass def test_not_my_file(self): pass def test_almost_my_file(self): pass def test_pprint(self): pass def test_mime(self): pass
12
0
5
0
5
0
1
0
1
4
3
0
11
4
11
86
72
11
61
16
49
0
52
16
40
1
3
0
11
146,903
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.TimeStampSpec
class TimeStampSpec(EncodedTextSpec): def read(self, frame, data): # EncodedTextSpec.read returns str, bytes value, data = super(TimeStampSpec, self).read(frame, data) return self.validate(frame, value), data def write(self, frame, data): return super(TimeStampSpec, self).write(frame, data.text.replace(' ', 'T')) def validate(self, frame, value): try: return ID3TimeStamp(value) except TypeError: raise ValueError("Invalid ID3TimeStamp: %r" % value)
class TimeStampSpec(EncodedTextSpec): def read(self, frame, data): pass def write(self, frame, data): pass def validate(self, frame, value): pass
4
0
4
0
4
0
1
0.08
1
4
1
0
3
0
3
9
15
2
12
5
8
1
11
5
7
2
3
1
4
146,904
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp3.py
tests.test_mp3.TMP3
class TMP3(TestCase): silence = os.path.join('tests', 'data', 'silence-44-s.mp3') silence_nov2 = os.path.join('tests', 'data', 'silence-44-s-v1.mp3') silence_mpeg2 = os.path.join('tests', 'data', 'silence-44-s-mpeg2.mp3') silence_mpeg25 = os.path.join('tests', 'data', 'silence-44-s-mpeg25.mp3') def setUp(self): original = os.path.join("tests", "data", "silence-44-s.mp3") fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(original, self.filename) self.mp3 = MP3(self.filename) self.mp3_2 = MP3(self.silence_nov2) self.mp3_3 = MP3(self.silence_mpeg2) self.mp3_4 = MP3(self.silence_mpeg25) def test_mode(self): from mutagen.mp3 import JOINTSTEREO self.failUnlessEqual(self.mp3.info.mode, JOINTSTEREO) self.failUnlessEqual(self.mp3_2.info.mode, JOINTSTEREO) self.failUnlessEqual(self.mp3_3.info.mode, JOINTSTEREO) self.failUnlessEqual(self.mp3_4.info.mode, JOINTSTEREO) def test_id3(self): self.failUnlessEqual(self.mp3.tags, ID3(self.silence)) self.failUnlessEqual(self.mp3_2.tags, ID3(self.silence_nov2)) def test_length(self): self.assertAlmostEquals(self.mp3.info.length, 3.77, 2) self.assertAlmostEquals(self.mp3_2.info.length, 3.77, 2) self.assertAlmostEquals(self.mp3_3.info.length, 3.77, 2) self.assertAlmostEquals(self.mp3_4.info.length, 3.84, 2) def test_version(self): self.failUnlessEqual(self.mp3.info.version, 1) self.failUnlessEqual(self.mp3_2.info.version, 1) self.failUnlessEqual(self.mp3_3.info.version, 2) self.failUnlessEqual(self.mp3_4.info.version, 2.5) def test_layer(self): self.failUnlessEqual(self.mp3.info.layer, 3) self.failUnlessEqual(self.mp3_2.info.layer, 3) self.failUnlessEqual(self.mp3_3.info.layer, 3) self.failUnlessEqual(self.mp3_4.info.layer, 3) def test_bitrate(self): self.failUnlessEqual(self.mp3.info.bitrate, 32000) self.failUnlessEqual(self.mp3_2.info.bitrate, 32000) self.failUnlessEqual(self.mp3_3.info.bitrate, 18191) self.failUnlessEqual(self.mp3_4.info.bitrate, 9300) def test_notmp3(self): self.failUnlessRaises( MP3Error, MP3, os.path.join('tests', 'data', 'empty.ofr')) def test_sketchy(self): self.failIf(self.mp3.info.sketchy) self.failIf(self.mp3_2.info.sketchy) self.failIf(self.mp3_3.info.sketchy) self.failIf(self.mp3_4.info.sketchy) def test_sketchy_notmp3(self): notmp3 = MP3(os.path.join("tests", "data", "silence-44-s.flac")) self.failUnless(notmp3.info.sketchy) def test_pprint(self): self.failUnless(self.mp3.pprint()) def test_pprint_no_tags(self): self.mp3.tags = None self.failUnless(self.mp3.pprint()) def test_xing(self): mp3 = MP3(os.path.join("tests", "data", "xing.mp3")) self.failUnlessEqual(int(round(mp3.info.length)), 26122) self.failUnlessEqual(mp3.info.bitrate, 306) def test_vbri(self): mp3 = MP3(os.path.join("tests", "data", "vbri.mp3")) self.failUnlessEqual(int(round(mp3.info.length)), 222) def test_empty_xing(self): MP3(os.path.join("tests", "data", "bad-xing.mp3")) def test_delete(self): self.mp3.delete() self.failIf(self.mp3.tags) self.failUnless(MP3(self.filename).tags is None) def test_module_delete(self): delete(self.filename) self.failUnless(MP3(self.filename).tags is None) def test_save(self): self.mp3["TIT1"].text = ["foobar"] self.mp3.save() self.failUnless(MP3(self.filename)["TIT1"] == "foobar") def test_load_non_id3(self): filename = os.path.join("tests", "data", "apev2-lyricsv2.mp3") from mutagen.apev2 import APEv2 mp3 = MP3(filename, ID3=APEv2) self.failUnless("replaygain_track_peak" in mp3.tags) def test_add_tags(self): mp3 = MP3(os.path.join("tests", "data", "xing.mp3")) self.failIf(mp3.tags) mp3.add_tags() self.failUnless(isinstance(mp3.tags, ID3)) def test_add_tags_already_there(self): mp3 = MP3(os.path.join("tests", "data", "silence-44-s.mp3")) self.failUnless(mp3.tags) self.failUnlessRaises(Exception, mp3.add_tags) def test_save_no_tags(self): self.mp3.tags = None self.failUnlessRaises(ValueError, self.mp3.save) def test_mime(self): self.failUnless("audio/mp3" in self.mp3.mime) # XXX self.mp3.info.layer = 2 self.failIf("audio/mp3" in self.mp3.mime) self.failUnless("audio/mp2" in self.mp3.mime) def tearDown(self): os.unlink(self.filename)
class TMP3(TestCase): def setUp(self): pass def test_mode(self): pass def test_id3(self): pass def test_length(self): pass def test_version(self): pass def test_layer(self): pass def test_bitrate(self): pass def test_notmp3(self): pass def test_sketchy(self): pass def test_sketchy_notmp3(self): pass def test_pprint(self): pass def test_pprint_no_tags(self): pass def test_xing(self): pass def test_vbri(self): pass def test_empty_xing(self): pass def test_delete(self): pass def test_module_delete(self): pass def test_save(self): pass def test_load_non_id3(self): pass def test_add_tags(self): pass def test_add_tags_already_there(self): pass def test_save_no_tags(self): pass def test_mime(self): pass def tearDown(self): pass
25
0
4
0
4
0
1
0.01
1
6
3
0
24
5
24
99
125
21
103
44
76
1
102
44
75
1
3
0
24
146,905
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.StringSpec
class StringSpec(Spec): def __init__(self, name, length): super(StringSpec, self).__init__(name) self.len = length def read(s, frame, data): return data[:s.len].decode('latin1'), data[s.len:] def write(s, frame, value): if value is None: return b'\x00' * s.len else: return (value.encode('latin1') + b'\x00' * s.len)[:s.len] def validate(s, frame, value): if value is None: return None if not isinstance(value, text_type): value = value.decode("ascii") if len(value) == s.len: return value raise ValueError('Invalid StringSpec[%d] data: %r' % (s.len, value))
class StringSpec(Spec): def __init__(self, name, length): pass def read(s, frame, data): pass def write(s, frame, value): pass def validate(s, frame, value): pass
5
0
5
1
5
0
2
0
1
2
0
0
4
1
4
7
24
5
19
6
14
0
18
6
13
4
2
1
8
146,906
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.TestV22Tags
class TestV22Tags(TestCase): def setUp(self): filename = os.path.join("tests", "data", "id3v22-test.mp3") self.tags = ID3(filename) def test_tags(self): self.failUnless(self.tags["TRCK"].text == ["3/11"]) self.failUnless(self.tags["TPE1"].text == ["Anais Mitchell"])
class TestV22Tags(TestCase): def setUp(self): pass def test_tags(self): pass
3
0
3
0
3
0
1
0
1
1
1
0
2
1
2
77
9
2
7
5
4
0
7
5
4
1
3
0
2
146,907
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.TestWriteID3v1
class TestWriteID3v1(TestCase): SILENCE = os.path.join("tests", "data", "silence-44-s.mp3") def setUp(self): from tempfile import mkstemp fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(self.SILENCE, self.filename) self.audio = ID3(self.filename) def failIfV1(self): fileobj = open(self.filename, "rb") fileobj.seek(-128, 2) self.failIf(fileobj.read(3) == b"TAG") def failUnlessV1(self): fileobj = open(self.filename, "rb") fileobj.seek(-128, 2) self.failUnless(fileobj.read(3) == b"TAG") def test_save_delete(self): self.audio.save(v1=0) self.failIfV1() def test_save_add(self): self.audio.save(v1=2) self.failUnlessV1() def test_save_defaults(self): self.audio.save(v1=0) self.failIfV1() self.audio.save(v1=1) self.failIfV1() self.audio.save(v1=2) self.failUnlessV1() self.audio.save(v1=1) self.failUnlessV1() def tearDown(self): os.unlink(self.filename)
class TestWriteID3v1(TestCase): def setUp(self): pass def failIfV1(self): pass def failUnlessV1(self): pass def test_save_delete(self): pass def test_save_add(self): pass def test_save_defaults(self): pass def tearDown(self): pass
8
0
4
0
4
0
1
0
1
1
1
0
7
2
7
82
39
6
33
14
24
0
33
14
24
1
3
0
7
146,908
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.RVRB
class RVRB(Frame): """Reverb.""" _framespec = [ SizedIntegerSpec('left', 2), SizedIntegerSpec('right', 2), ByteSpec('bounce_left'), ByteSpec('bounce_right'), ByteSpec('feedback_ltl'), ByteSpec('feedback_ltr'), ByteSpec('feedback_rtr'), ByteSpec('feedback_rtl'), ByteSpec('premix_ltr'), ByteSpec('premix_rtl'), ] def __eq__(self, other): return (self.left, self.right) == other __hash__ = Frame.__hash__
class RVRB(Frame): '''Reverb.''' def __eq__(self, other): pass
2
1
2
0
2
0
1
0.06
1
0
0
1
1
0
1
14
20
3
16
4
14
1
5
4
3
1
2
0
1
146,909
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.RVA2
class RVA2(Frame): """Relative volume adjustment (2). This frame is used to implemented volume scaling, and in particular, normalization using ReplayGain. Attributes: * desc -- description or context of this adjustment * channel -- audio channel to adjust (master is 1) * gain -- a + or - dB gain relative to some reference level * peak -- peak of the audio as a floating point number, [0, 1] When storing ReplayGain tags, use descriptions of 'album' and 'track' on channel 1. """ _framespec = [ Latin1TextSpec('desc'), ChannelSpec('channel'), VolumeAdjustmentSpec('gain'), VolumePeakSpec('peak'), ] _channels = ["Other", "Master volume", "Front right", "Front left", "Back right", "Back left", "Front centre", "Back centre", "Subwoofer"] @property def HashKey(self): return '%s:%s' % (self.FrameID, self.desc) def __eq__(self, other): try: return ((str(self) == other) or (self.desc == other.desc and self.channel == other.channel and self.gain == other.gain and self.peak == other.peak)) except AttributeError: return False __hash__ = Frame.__hash__ def __str__(self): return "%s: %+0.4f dB/%0.4f" % ( self._channels[self.channel], self.gain, self.peak)
class RVA2(Frame): '''Relative volume adjustment (2). This frame is used to implemented volume scaling, and in particular, normalization using ReplayGain. Attributes: * desc -- description or context of this adjustment * channel -- audio channel to adjust (master is 1) * gain -- a + or - dB gain relative to some reference level * peak -- peak of the audio as a floating point number, [0, 1] When storing ReplayGain tags, use descriptions of 'album' and 'track' on channel 1. ''' @property def HashKey(self): pass def __eq__(self, other): pass def __str__(self): pass
5
1
5
0
5
0
1
0.42
1
2
0
0
3
0
3
16
47
10
26
8
21
11
13
7
9
2
2
1
4
146,910
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.UpdateTo23
class UpdateTo23(TestCase): def test_tdrc(self): tags = ID3() tags.add(id3.TDRC(encoding=1, text="2003-04-05 12:03")) tags.update_to_v23() self.failUnlessEqual(tags["TYER"].text, ["2003"]) self.failUnlessEqual(tags["TDAT"].text, ["0504"]) self.failUnlessEqual(tags["TIME"].text, ["1203"]) def test_tdor(self): tags = ID3() tags.add(id3.TDOR(encoding=1, text="2003-04-05 12:03")) tags.update_to_v23() self.failUnlessEqual(tags["TORY"].text, ["2003"]) def test_genre_from_v24_1(self): tags = ID3() tags.add(id3.TCON(encoding=1, text=["4","Rock"])) tags.update_to_v23() self.failUnlessEqual(tags["TCON"].text, ["Disco", "Rock"]) def test_genre_from_v24_2(self): tags = ID3() tags.add(id3.TCON(encoding=1, text=["RX", "3", "CR"])) tags.update_to_v23() self.failUnlessEqual(tags["TCON"].text, ["Remix", "Dance", "Cover"]) def test_genre_from_v23_1(self): tags = ID3() tags.add(id3.TCON(encoding=1, text=["(4)Rock"])) tags.update_to_v23() self.failUnlessEqual(tags["TCON"].text, ["Disco", "Rock"]) def test_genre_from_v23_2(self): tags = ID3() tags.add(id3.TCON(encoding=1, text=["(RX)(3)(CR)"])) tags.update_to_v23() self.failUnlessEqual(tags["TCON"].text, ["Remix", "Dance", "Cover"]) def test_ipls(self): tags = ID3() tags.version = (2, 3) tags.add(id3.TIPL(encoding=0, people=[["a", "b"], ["c", "d"]])) tags.add(id3.TMCL(encoding=0, people=[["e", "f"], ["g", "h"]])) tags.update_to_v23() self.failUnlessEqual(tags["IPLS"], [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]])
class UpdateTo23(TestCase): def test_tdrc(self): pass def test_tdor(self): pass def test_genre_from_v24_1(self): pass def test_genre_from_v24_2(self): pass def test_genre_from_v23_1(self): pass def test_genre_from_v23_2(self): pass def test_ipls(self): pass
8
0
6
0
6
0
1
0
1
6
6
0
7
0
7
82
48
7
41
15
33
0
40
15
32
1
3
0
7
146,911
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.UpdateTo24
class UpdateTo24(TestCase): def test_pic(self): from mutagen.id3 import PIC id3 = ID3() id3.version = (2, 2) id3.add(PIC(encoding=0, mime=b"PNG", desc="cover", type=3, data=b"")) id3.update_to_v24() self.failUnlessEqual(id3["APIC:cover"].mime, "image/png") def test_tyer(self): from mutagen.id3 import TYER id3 = ID3() id3.version = (2, 3) id3.add(TYER(encoding=0, text="2006")) id3.update_to_v24() self.failUnlessEqual(id3["TDRC"], "2006") def test_tyer_tdat(self): from mutagen.id3 import TYER, TDAT id3 = ID3() id3.version = (2, 3) id3.add(TYER(encoding=0, text="2006")) id3.add(TDAT(encoding=0, text="0603")) id3.update_to_v24() self.failUnlessEqual(id3["TDRC"], "2006-03-06") def test_tyer_tdat_time(self): from mutagen.id3 import TYER, TDAT, TIME id3 = ID3() id3.version = (2, 3) id3.add(TYER(encoding=0, text="2006")) id3.add(TDAT(encoding=0, text="0603")) id3.add(TIME(encoding=0, text="1127")) id3.update_to_v24() self.failUnlessEqual(id3["TDRC"], "2006-03-06 11:27:00") def test_tory(self): from mutagen.id3 import TORY id3 = ID3() id3.version = (2, 3) id3.add(TORY(encoding=0, text="2006")) id3.update_to_v24() self.failUnlessEqual(id3["TDOR"], "2006") def test_ipls(self): from mutagen.id3 import IPLS id3 = ID3() id3.version = (2, 3) id3.add(IPLS(encoding=0, people=[["a", "b"], ["c", "d"]])) id3.update_to_v24() self.failUnlessEqual(id3["TIPL"], [["a", "b"], ["c", "d"]]) def test_dropped(self): from mutagen.id3 import TIME id3 = ID3() id3.version = (2, 3) id3.add(TIME(encoding=0, text=["1155"])) id3.update_to_v24() self.assertFalse(id3.getall("TIME"))
class UpdateTo24(TestCase): def test_pic(self): pass def test_tyer(self): pass def test_tyer_tdat(self): pass def test_tyer_tdat_time(self): pass def test_tory(self): pass def test_ipls(self): pass def test_dropped(self): pass
8
0
7
0
7
0
1
0
1
7
7
0
7
0
7
82
60
7
53
22
38
0
53
22
38
1
3
0
7
146,912
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.WriteForEyeD3
class WriteForEyeD3(TestCase): silence = join('tests', 'data', 'silence-44-s.mp3') newsilence = join('tests', 'data', 'silence-written.mp3') def setUp(self): shutil.copy(self.silence, self.newsilence) # remove ID3v1 tag f = open(self.newsilence, "rb+") f.seek(-128, 2) f.truncate() f.close() def test_same(self): ID3(self.newsilence).save() id3 = eyeD3.tag.Tag(eyeD3.ID3_V2_4) id3.link(self.newsilence) self.assertEquals(id3.frames["TALB"][0].text, "Quod Libet Test Data") self.assertEquals(id3.frames["TCON"][0].text, "Silence") self.assertEquals(id3.frames["TIT2"][0].text, "Silence") # "piman" should have been cleared self.assertEquals(len(id3.frames["TPE1"]), 1) self.assertEquals(id3.frames["TPE1"][0].text, "jzig") def test_addframe(self): from mutagen.id3 import TIT3 f = ID3(self.newsilence) self.assert_("TIT3" not in f) f["TIT3"] = TIT3(encoding=0, text="A subtitle!") f.save() id3 = eyeD3.tag.Tag(eyeD3.ID3_V2_4) id3.link(self.newsilence) self.assertEquals(id3.frames["TIT3"][0].text, "A subtitle!") def test_changeframe(self): f = ID3(self.newsilence) self.assertEquals(f["TIT2"], "Silence") f["TIT2"].text = [u"The sound of silence."] f.save() id3 = eyeD3.tag.Tag(eyeD3.ID3_V2_4) id3.link(self.newsilence) self.assertEquals(id3.frames["TIT2"][0].text, "The sound of silence.") def tearDown(self): os.unlink(self.newsilence)
class WriteForEyeD3(TestCase): def setUp(self): pass def test_same(self): pass def test_addframe(self): pass def test_changeframe(self): pass def tearDown(self): pass
6
0
7
0
7
0
1
0.05
1
2
2
0
5
0
5
80
44
5
37
15
30
2
37
15
30
1
3
0
5
146,913
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.WriteRoundtrip
class WriteRoundtrip(TestCase): silence = join('tests', 'data', 'silence-44-s.mp3') newsilence = join('tests', 'data', 'silence-written.mp3') def setUp(self): shutil.copy(self.silence, self.newsilence) def test_same(self): ID3(self.newsilence).save() id3 = ID3(self.newsilence) self.assertEquals(id3["TALB"], "Quod Libet Test Data") self.assertEquals(id3["TCON"], "Silence") self.assertEquals(id3["TIT2"], "Silence") self.assertEquals(id3["TPE1"], ["jzig"]) def test_same_v23(self): id3 = ID3(self.newsilence, v2_version=3) id3.save(v2_version=3) id3 = ID3(self.newsilence) self.assertEqual(id3.version, id3._V23) self.assertEquals(id3["TALB"], "Quod Libet Test Data") self.assertEquals(id3["TCON"], "Silence") self.assertEquals(id3["TIT2"], "Silence") self.assertEquals(id3["TPE1"], "jzig") def test_addframe(self): from mutagen.id3 import TIT3 f = ID3(self.newsilence) self.assert_("TIT3" not in f) f["TIT3"] = TIT3(encoding=0, text="A subtitle!") f.save() id3 = ID3(self.newsilence) self.assertEquals(id3["TIT3"], "A subtitle!") def test_changeframe(self): f = ID3(self.newsilence) self.assertEquals(f["TIT2"], "Silence") f["TIT2"].text = [u"The sound of silence."] f.save() id3 = ID3(self.newsilence) self.assertEquals(id3["TIT2"], "The sound of silence.") def test_replaceframe(self): from mutagen.id3 import TPE1 f = ID3(self.newsilence) self.assertEquals(f["TPE1"], "jzig") f["TPE1"] = TPE1(encoding=0, text=u"jzig\x00piman") f.save() id3 = ID3(self.newsilence) self.assertEquals(id3["TPE1"], ["jzig", "piman"]) def test_compressibly_large(self): from mutagen.id3 import TPE2 f = ID3(self.newsilence) self.assert_("TPE2" not in f) f["TPE2"] = TPE2(encoding=0, text="Ab" * 1025) f.save() id3 = ID3(self.newsilence) self.assertEquals(id3["TPE2"], "Ab" * 1025) def test_nofile_emptytag(self): os.unlink(self.newsilence) ID3().save(self.newsilence) self.assertRaises(EnvironmentError, open, self.newsilence) def test_nofile_silencetag(self): id3 = ID3(self.newsilence) os.unlink(self.newsilence) id3.save(self.newsilence) self.assertEquals(b'ID3', open(self.newsilence, "rb").read(3)) self.test_same() def test_emptyfile_silencetag(self): id3 = ID3(self.newsilence) open(self.newsilence, 'wb').truncate() id3.save(self.newsilence) self.assertEquals(b'ID3', open(self.newsilence, "rb").read(3)) self.test_same() def test_empty_plustag_minustag_empty(self): id3 = ID3(self.newsilence) open(self.newsilence, 'wb').truncate() id3.save() id3.delete() self.failIf(id3) self.assertEquals(open(self.newsilence, "rb").read(10), b'') def test_empty_plustag_emptytag_empty(self): id3 = ID3(self.newsilence) open(self.newsilence, 'wb').truncate() id3.save() id3.clear() id3.save() self.assertEquals(open(self.newsilence, "rb").read(10), b'') def test_delete_invalid_zero(self): f = open(self.newsilence, 'wb') f.write(b'ID3\x04\x00\x00\x00\x00\x00\x00abc') f.close() ID3(self.newsilence).delete() self.assertEquals(open(self.newsilence, "rb").read(10), b'abc') def test_frame_order(self): from mutagen.id3 import TIT2, APIC, TALB, COMM f = ID3(self.newsilence) f["TIT2"] = TIT2(encoding=0, text="A title!") f["APIC"] = APIC(encoding=0, mime="b", type=3, desc='', data=b"a") f["TALB"] = TALB(encoding=0, text="c") f["COMM"] = COMM(encoding=0, desc="x", text="y") f.save() data = open(self.newsilence, 'rb').read() self.assert_(data.find(b"TIT2") < data.find(b"APIC")) self.assert_(data.find(b"TIT2") < data.find(b"COMM")) self.assert_(data.find(b"TALB") < data.find(b"APIC")) self.assert_(data.find(b"TALB") < data.find(b"COMM")) self.assert_(data.find(b"TIT2") < data.find(b"TALB")) def tearDown(self): try: os.unlink(self.newsilence) except EnvironmentError: pass
class WriteRoundtrip(TestCase): def setUp(self): pass def test_same(self): pass def test_same_v23(self): pass def test_addframe(self): pass def test_changeframe(self): pass def test_replaceframe(self): pass def test_compressibly_large(self): pass def test_nofile_emptytag(self): pass def test_nofile_silencetag(self): pass def test_emptyfile_silencetag(self): pass def test_empty_plustag_minustag_empty(self): pass def test_empty_plustag_emptytag_empty(self): pass def test_delete_invalid_zero(self): pass def test_frame_order(self): pass def tearDown(self): pass
16
0
7
0
7
0
1
0
1
8
8
0
15
0
15
90
119
14
105
39
85
0
107
39
87
2
3
1
16
146,914
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_id3.py
tests.test_id3.WriteTo23
class WriteTo23(TestCase): SILENCE = os.path.join("tests", "data", "silence-44-s.mp3") def setUp(self): from tempfile import mkstemp fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(self.SILENCE, self.filename) self.audio = ID3(self.filename) def tearDown(self): os.unlink(self.filename) def test_update_to_v23_on_load(self): from mutagen.id3 import TSOT self.audio.add(TSOT(text=["Ha"], encoding=3)) self.audio.save() # update_to_v23 called id3 = ID3(self.filename, v2_version=3) self.assertFalse(id3.getall("TSOT")) # update_to_v23 not called id3 = ID3(self.filename, v2_version=3, translate=False) self.assertTrue(id3.getall("TSOT")) def test_load_save_inval_version(self): self.assertRaises(ValueError, self.audio.save, v2_version=5) self.assertRaises(ValueError, ID3, self.filename, v2_version=5) def test_save(self): strings = ["one", "two", "three"] from mutagen.id3 import TPE1 self.audio.add(TPE1(text=strings, encoding=3)) self.audio.save(v2_version=3) frame = self.audio["TPE1"] self.assertEqual(frame.encoding, 3) self.assertEqual(frame.text, strings) id3 = ID3(self.filename, translate=False) self.assertEqual(id3.version, (2, 3, 0)) frame = id3["TPE1"] self.assertEqual(frame.encoding, 1) self.assertEqual(frame.text, ["/".join(strings)]) # null separator, mutagen can still read it self.audio.save(v2_version=3, v23_sep=None) id3 = ID3(self.filename, translate=False) self.assertEqual(id3.version, (2, 3, 0)) frame = id3["TPE1"] self.assertEqual(frame.encoding, 1) self.assertEqual(frame.text, strings) def test_save_off_spec_frames(self): # These are not defined in v2.3 and shouldn't be written. # Still make sure reading them again works and the encoding # is at least changed from mutagen.id3 import TDEN, TIPL dates = ["2013", "2014"] frame = TDEN(text=dates, encoding=3) self.audio.add(frame) tipl_frame = TIPL(people=[("a", "b"), ("c", "d")], encoding=2) self.audio.add(tipl_frame) self.audio.save(v2_version=3) id3 = ID3(self.filename, translate=False) self.assertEqual(id3.version, (2, 3, 0)) self.assertEqual([stamp.text for stamp in id3["TDEN"].text], dates) self.assertEqual(id3["TDEN"].encoding, 1) self.assertEqual(id3["TIPL"].people, tipl_frame.people) self.assertEqual(id3["TIPL"].encoding, 1)
class WriteTo23(TestCase): def setUp(self): pass def tearDown(self): pass def test_update_to_v23_on_load(self): pass def test_load_save_inval_version(self): pass def test_save(self): pass def test_save_off_spec_frames(self): pass
7
0
11
2
9
1
1
0.11
1
6
5
0
6
2
6
81
77
17
54
22
43
6
54
22
43
1
3
0
6
146,915
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_monkeysaudio.py
tests.test_monkeysaudio.TMonkeysAudio
class TMonkeysAudio(TestCase): def setUp(self): self.mac399 = MonkeysAudio(os.path.join("tests", "data", "mac-399.ape")) self.mac396 = MonkeysAudio(os.path.join("tests", "data", "mac-396.ape")) self.mac390 = MonkeysAudio(os.path.join("tests", "data", "mac-390-hdr.ape")) def test_channels(self): self.failUnlessEqual(self.mac399.info.channels, 2) self.failUnlessEqual(self.mac396.info.channels, 2) self.failUnlessEqual(self.mac390.info.channels, 2) def test_sample_rate(self): self.failUnlessEqual(self.mac399.info.sample_rate, 44100) self.failUnlessEqual(self.mac396.info.sample_rate, 44100) self.failUnlessEqual(self.mac390.info.sample_rate, 44100) def test_length(self): self.failUnlessAlmostEqual(self.mac399.info.length, 3.68, 2) self.failUnlessAlmostEqual(self.mac396.info.length, 3.68, 2) self.failUnlessAlmostEqual(self.mac390.info.length, 15.63, 2) def test_version(self): self.failUnlessEqual(self.mac399.info.version, 3.99) self.failUnlessEqual(self.mac396.info.version, 3.96) self.failUnlessEqual(self.mac390.info.version, 3.90) def test_not_my_file(self): self.failUnlessRaises( MonkeysAudioHeaderError, MonkeysAudio, os.path.join("tests", "data", "empty.ogg")) self.failUnlessRaises( MonkeysAudioHeaderError, MonkeysAudio, os.path.join("tests", "data", "click.mpc")) def test_mime(self): self.failUnless("audio/x-ape" in self.mac399.mime) def test_pprint(self): self.failUnless(self.mac399.pprint()) self.failUnless(self.mac396.pprint())
class TMonkeysAudio(TestCase): def setUp(self): pass def test_channels(self): pass def test_sample_rate(self): pass def test_length(self): pass def test_version(self): pass def test_not_my_file(self): pass def test_mime(self): pass def test_pprint(self): pass
9
0
4
0
4
0
1
0
1
2
2
0
8
3
8
83
44
8
36
12
27
0
29
12
20
1
3
0
8
146,916
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp3.py
tests.test_mp3.Issue72_TooShortFile
class Issue72_TooShortFile(TestCase): def test_load(self): mp3 = MP3(os.path.join('tests', 'data', 'too-short.mp3')) self.failUnlessEqual(mp3["TIT2"], "Track 10") self.failUnlessAlmostEqual(mp3.info.length, 0.03, 2)
class Issue72_TooShortFile(TestCase): def test_load(self): pass
2
0
4
0
4
0
1
0
1
1
1
0
1
0
1
76
5
0
5
3
3
0
5
3
3
1
3
0
1
146,917
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_mp3.py
tests.test_mp3.TEasyMP3
class TEasyMP3(TestCase): def setUp(self): original = os.path.join("tests", "data", "silence-44-s.mp3") fd, self.filename = mkstemp(suffix='.mp3') os.close(fd) shutil.copy(original, self.filename) self.mp3 = EasyMP3(self.filename) def test_artist(self): self.failUnless("artist" in self.mp3) def test_no_composer(self): self.failIf("composer" in self.mp3) def test_length(self): # http://code.google.com/p/mutagen/issues/detail?id=125 # easyid3, normal id3 and mpeg loading without tags should skip # the tags and get the right offset of the first frame easy = self.mp3.info noneasy = MP3(self.filename).info nonid3 = MPEGInfo(open(self.filename, "rb")) self.failUnlessEqual(easy.length, noneasy.length) self.failUnlessEqual(noneasy.length, nonid3.length) def tearDown(self): os.unlink(self.filename)
class TEasyMP3(TestCase): def setUp(self): pass def test_artist(self): pass def test_no_composer(self): pass def test_length(self): pass def tearDown(self): pass
6
0
4
0
4
1
1
0.16
1
3
3
0
5
2
5
80
28
6
19
12
13
3
19
12
13
1
3
0
5
146,918
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.SynchronizedTextSpec
class SynchronizedTextSpec(EncodedTextSpec): def read(self, frame, data): texts = [] encoding, term = self._encodings[frame.encoding] while data: try: value, data = decode_terminated(data, encoding) except ValueError: raise ID3JunkFrameError if len(data) < 4: raise ID3JunkFrameError time, = struct.unpack(">I", data[:4]) texts.append((value, time)) data = data[4:] return texts, b'' def write(self, frame, value): data = [] encoding, term = self._encodings[frame.encoding] for text, time in value: text = text.encode(encoding) + term data.append(text + struct.pack(">I", time)) return b"".join(data) def validate(self, frame, value): return value
class SynchronizedTextSpec(EncodedTextSpec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
8
1
8
0
2
0
1
2
1
0
3
0
3
9
28
4
24
11
20
0
24
11
20
4
3
2
7
146,919
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.UrlFrame
class UrlFrame(Frame): """A frame containing a URL string. The ID3 specification is silent about IRIs and normalized URL forms. Mutagen assumes all URLs in files are encoded as Latin 1, but string conversion of this frame returns a UTF-8 representation for compatibility with other string conversions. The only sane way to handle URLs in MP3s is to restrict them to ASCII. """ _framespec = [Latin1TextSpec('url')] def __bytes__(self): return self.url.encode('utf-8') def __str__(self): return self.url def __eq__(self, other): return self.url == other __hash__ = Frame.__hash__ def _pprint(self): return self.url
class UrlFrame(Frame): '''A frame containing a URL string. The ID3 specification is silent about IRIs and normalized URL forms. Mutagen assumes all URLs in files are encoded as Latin 1, but string conversion of this frame returns a UTF-8 representation for compatibility with other string conversions. The only sane way to handle URLs in MP3s is to restrict them to ASCII. ''' def __bytes__(self): pass def __str__(self): pass def __eq__(self, other): pass def _pprint(self): pass
5
1
2
0
2
0
1
0.73
1
0
0
9
4
0
4
17
27
8
11
7
6
8
11
7
6
1
2
0
4
146,920
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.ASPIIndexSpec
class ASPIIndexSpec(Spec): def read(self, frame, data): if frame.b == 16: format = "H" size = 2 elif frame.b == 8: format = "B" size = 1 else: warn("invalid bit count in ASPI (%d)" % frame.b, ID3Warning) return [], data indexes = data[:frame.N * size] data = data[frame.N * size:] return list(struct.unpack(">" + format * frame.N, indexes)), data def write(self, frame, values): if frame.b == 16: format = "H" elif frame.b == 8: format = "B" else: raise ValueError("frame.b must be 8 or 16") return struct.pack(">" + format * frame.N, *values) def validate(self, frame, values): return values
class ASPIIndexSpec(Spec): def read(self, frame, data): pass def write(self, frame, values): pass def validate(self, frame, values): pass
4
0
8
0
8
0
2
0
1
3
1
0
3
0
3
6
27
3
24
6
20
0
20
6
16
3
2
1
7
146,921
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.BinaryDataSpec
class BinaryDataSpec(Spec): def read(self, frame, data): return data, b'' def write(self, frame, value): if value is None: return b"" if isinstance(value, bytes): return value value = text_type(value).encode("ascii") return value def validate(self, frame, value): if isinstance(value, bytes): return value value = text_type(value).encode("ascii") return value
class BinaryDataSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
5
0
5
0
2
0
1
1
0
0
3
0
3
6
17
2
15
4
11
0
15
4
11
3
2
1
6
146,922
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.ByteSpec
class ByteSpec(Spec): def read(self, frame, data): return bytearray(data)[0], data[1:] def write(self, frame, value): return chr_(value) def validate(self, frame, value): if value is not None: chr_(value) return value
class ByteSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
3
0
3
0
1
0
1
1
0
2
3
0
3
6
11
2
9
4
5
0
9
4
5
2
2
1
4
146,923
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.EncodedTextSpec
class EncodedTextSpec(Spec): # Okay, seriously. This is private and defined explicitly and # completely by the ID3 specification. You can't just add # encodings here however you want. _encodings = ( ('latin1', b'\x00'), ('utf16', b'\x00\x00'), ('utf_16_be', b'\x00\x00'), ('utf8', b'\x00') ) def read(self, frame, data): enc, term = self._encodings[frame.encoding] try: # allow missing termination return decode_terminated(data, enc, strict=False) except ValueError: # utf-16 termination with missing BOM, or single NULL if not data[:len(term)].strip(b"\x00"): return u"", data[len(term):] # utf-16 data with single NULL, see issue 169 try: return decode_terminated(data + b"\x00", enc) except ValueError: raise ID3JunkFrameError def write(self, frame, value): enc, term = self._encodings[frame.encoding] return value.encode(enc) + term def validate(self, frame, value): return text_type(value)
class EncodedTextSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
7
0
5
1
2
0.26
1
2
1
5
3
0
3
6
33
4
23
7
19
6
18
7
14
4
2
2
6
146,924
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.EncodingSpec
class EncodingSpec(ByteSpec): def read(self, frame, data): enc, data = super(EncodingSpec, self).read(frame, data) if enc < 16: return enc, data else: return 0, chr_(enc) + data def validate(self, frame, value): if value is None: return None if 0 <= value <= 3: return value raise ValueError('Invalid Encoding: %r' % value) def _validate23(self, frame, value, **kwargs): # only 0, 1 are valid in v2.3, default to utf-16 return min(1, value)
class EncodingSpec(ByteSpec): def read(self, frame, data): pass def validate(self, frame, value): pass def _validate23(self, frame, value, **kwargs): pass
4
0
5
0
5
0
2
0.07
1
2
0
0
3
0
3
9
18
2
15
5
11
1
14
5
10
3
3
1
6
146,925
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.ID3TimeStamp
class ID3TimeStamp(object): """A time stamp in ID3v2 format. This is a restricted form of the ISO 8601 standard; time stamps take the form of: YYYY-MM-DD HH:MM:SS Or some partial form (YYYY-MM-DD HH, YYYY, etc.). The 'text' attribute contains the raw text data of the time stamp. """ import re def __init__(self, text): if isinstance(text, ID3TimeStamp): text = text.text elif not isinstance(text, text_type): if PY3: raise TypeError("not a str") text = text.decode("utf-8") self.text = text __formats = ['%04d'] + ['%02d'] * 5 __seps = ['-', '-', ' ', ':', ':', 'x'] def get_text(self): parts = [self.year, self.month, self.day, self.hour, self.minute, self.second] pieces = [] for i, part in enumerate(parts): if part is None: break pieces.append(self.__formats[i] % part + self.__seps[i]) return u''.join(pieces)[:-1] def set_text(self, text, splitre=re.compile('[-T:/.]|\s+')): year, month, day, hour, minute, second = \ splitre.split(text + ':::::')[:6] for a in 'year month day hour minute second'.split(): try: v = int(locals()[a]) except ValueError: v = None setattr(self, a, v) text = property(get_text, set_text, doc="ID3v2.4 date and time.") def __str__(self): return self.text def __bytes__(self): return self.text.encode("utf-8") def __repr__(self): return repr(self.text) def __eq__(self, other): return self.text == other.text def __lt__(self, other): return self.text < other.text __hash__ = object.__hash__ def encode(self, *args): return self.text.encode(*args)
class ID3TimeStamp(object): '''A time stamp in ID3v2 format. This is a restricted form of the ISO 8601 standard; time stamps take the form of: YYYY-MM-DD HH:MM:SS Or some partial form (YYYY-MM-DD HH, YYYY, etc.). The 'text' attribute contains the raw text data of the time stamp. ''' def __init__(self, text): pass def get_text(self): pass def set_text(self, text, splitre=re.compile('[-T:/.]|\s+')): pass def __str__(self): pass def __bytes__(self): pass def __repr__(self): pass def __eq__(self, other): pass def __lt__(self, other): pass def encode(self, *args): pass
10
1
4
0
4
0
2
0.16
1
4
0
0
9
0
9
9
67
16
44
21
33
7
41
21
30
4
1
2
16
146,926
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.IntegerSpec
class IntegerSpec(Spec): def read(self, frame, data): return int(BitPaddedInt(data, bits=8)), b'' def write(self, frame, value): return BitPaddedInt.to_str(value, bits=8, width=-1) def validate(self, frame, value): return value
class IntegerSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
2
0
2
0
1
0
1
2
1
0
3
0
3
6
9
2
7
4
3
0
7
4
3
1
2
0
3
146,927
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.KeyEventSpec
class KeyEventSpec(Spec): def read(self, frame, data): events = [] while len(data) >= 5: events.append(struct.unpack(">bI", data[:5])) data = data[5:] return events, data def write(self, frame, value): return b''.join(struct.pack(">bI", *event) for event in value) def validate(self, frame, value): return value
class KeyEventSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
6
13
2
11
5
7
0
11
5
7
2
2
1
4
146,928
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.Latin1TextSpec
class Latin1TextSpec(EncodedTextSpec): def read(self, frame, data): if b'\x00' in data: data, ret = data.split(b'\x00', 1) else: ret = b'' return data.decode('latin1'), ret def write(self, data, value): return value.encode('latin1') + b'\x00' def validate(self, frame, value): return text_type(value)
class Latin1TextSpec(EncodedTextSpec): def read(self, frame, data): pass def write(self, data, value): pass def validate(self, frame, value): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
9
13
2
11
5
7
0
10
5
6
2
3
1
4
146,929
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.MultiSpec
class MultiSpec(Spec): def __init__(self, name, *specs, **kw): super(MultiSpec, self).__init__(name) self.specs = specs self.sep = kw.get('sep') def read(self, frame, data): values = [] while data: record = [] for spec in self.specs: value, data = spec.read(frame, data) record.append(value) if len(self.specs) != 1: values.append(record) else: values.append(record[0]) return values, data def write(self, frame, value): data = [] if len(self.specs) == 1: for v in value: data.append(self.specs[0].write(frame, v)) else: for record in value: for v, s in zip(record, self.specs): data.append(s.write(frame, v)) return b''.join(data) def validate(self, frame, value): if value is None: return [] if self.sep and isinstance(value, string_types): value = value.split(self.sep) if isinstance(value, list): if len(self.specs) == 1: return [self.specs[0].validate(frame, v) for v in value] else: return [ [s.validate(frame, v) for (v, s) in zip(val, self.specs)] for val in value] raise ValueError('Invalid MultiSpec data: %r' % value) def _validate23(self, frame, value, **kwargs): if len(self.specs) != 1: return [[s._validate23(frame, v, **kwargs) for (v, s) in zip(val, self.specs)] for val in value] spec = self.specs[0] # Merge single text spec multispecs only. # (TimeStampSpec beeing the exception, but it's not a valid v2.3 frame) if not isinstance(spec, EncodedTextSpec) or \ isinstance(spec, TimeStampSpec): return value value = [spec._validate23(frame, v, **kwargs) for v in value] if kwargs.get("sep") is not None: return [spec.validate(frame, kwargs["sep"].join(value))] return value
class MultiSpec(Spec): def __init__(self, name, *specs, **kw): pass def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass def _validate23(self, frame, value, **kwargs): pass
6
0
11
1
10
0
4
0.04
1
6
2
0
5
2
5
8
62
7
53
17
47
2
45
17
39
5
2
3
19
146,930
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.SizedIntegerSpec
class SizedIntegerSpec(Spec): def __init__(self, name, size): self.name, self.__sz = name, size def read(self, frame, data): return int(BitPaddedInt(data[:self.__sz], bits=8)), data[self.__sz:] def write(self, frame, value): return BitPaddedInt.to_str(value, bits=8, width=self.__sz) def validate(self, frame, value): return value
class SizedIntegerSpec(Spec): def __init__(self, name, size): pass def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
5
0
2
0
2
0
1
0
1
2
1
0
4
2
4
7
12
3
9
6
4
0
9
6
4
1
2
0
4
146,931
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.Spec
class Spec(object): def __init__(self, name): self.name = name def __hash__(self): raise TypeError("Spec objects are unhashable") def _validate23(self, frame, value, **kwargs): """Return a possibly modified value which, if written, results in valid id3v2.3 data. """ return value
class Spec(object): def __init__(self, name): pass def __hash__(self): pass def _validate23(self, frame, value, **kwargs): '''Return a possibly modified value which, if written, results in valid id3v2.3 data. ''' pass
4
1
3
0
2
1
1
0.43
1
1
0
12
3
1
3
3
13
3
7
5
3
3
7
5
3
1
1
0
3
146,932
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.WXXX
class WXXX(UrlFrame): """User-defined URL data. Like TXXX, this has a freeform description associated with it. """ _framespec = [ EncodingSpec('encoding'), EncodedTextSpec('desc'), Latin1TextSpec('url'), ] @property def HashKey(self): return '%s:%s' % (self.FrameID, self.desc)
class WXXX(UrlFrame): '''User-defined URL data. Like TXXX, this has a freeform description associated with it. ''' @property def HashKey(self): pass
3
1
2
0
2
0
1
0.33
1
0
0
1
1
0
1
18
15
3
9
4
6
3
4
3
2
1
3
0
1
146,933
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.VolumeAdjustmentSpec
class VolumeAdjustmentSpec(Spec): def read(self, frame, data): value, = unpack('>h', data[0:2]) return value/512.0, data[2:] def write(self, frame, value): number = int(round(value * 512)) # pack only fails in 2.7, do it manually in 2.6 if not -32768 <= number <= 32767: raise struct.error return pack('>h', number) def validate(self, frame, value): if value is not None: try: self.write(frame, value) except struct.error: raise ValueError("out of range") return value
class VolumeAdjustmentSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
5
0
5
0
2
0.06
1
2
0
0
3
0
3
6
19
2
16
6
12
1
16
6
12
3
2
2
6
146,934
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/mp4.py
mutagen.mp4.Atoms
class Atoms(object): """Root atoms in a given file. Attributes: * atoms -- a list of top-level atoms as Atom objects This structure should only be used internally by Mutagen. """ def __init__(self, fileobj): self.atoms = [] fileobj.seek(0, 2) end = fileobj.tell() fileobj.seek(0) while fileobj.tell() + 8 <= end: self.atoms.append(Atom(fileobj)) def path(self, *names): """Look up and return the complete path of an atom. For example, atoms.path('moov', 'udta', 'meta') will return a list of three atoms, corresponding to the moov, udta, and meta atoms. """ path = [self] for name in names: path.append(path[-1][name, ]) return path[1:] def __contains__(self, names): try: self[names] except KeyError: return False return True def __getitem__(self, names): """Look up a child atom. 'names' may be a list of atoms (['moov', 'udta']) or a string specifying the complete path ('moov.udta'). """ if isinstance(names, bytes): names = names.split(b".") for child in self.atoms: if child.name == names[0]: return child[names[1:]] else: raise KeyError("%s not found" % names[0]) def __repr__(self): return '\n'.join(repr(child) for child in self.atoms)
class Atoms(object): '''Root atoms in a given file. Attributes: * atoms -- a list of top-level atoms as Atom objects This structure should only be used internally by Mutagen. ''' def __init__(self, fileobj): pass def path(self, *names): '''Look up and return the complete path of an atom. For example, atoms.path('moov', 'udta', 'meta') will return a list of three atoms, corresponding to the moov, udta, and meta atoms. ''' pass def __contains__(self, names): pass def __getitem__(self, names): '''Look up a child atom. 'names' may be a list of atoms (['moov', 'udta']) or a string specifying the complete path ('moov.udta'). ''' pass def __repr__(self): pass
6
3
8
1
6
2
2
0.48
1
3
1
0
5
1
5
5
54
11
29
11
23
14
29
11
23
4
1
2
11
146,935
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3specs.py
mutagen._id3specs.VolumePeakSpec
class VolumePeakSpec(Spec): def read(self, frame, data): # http://bugs.xmms.org/attachment.cgi?id=113&action=view peak = 0 data_array = bytearray(data) bits = data_array[0] vol_bytes = min(4, (bits + 7) >> 3) # not enough frame data if vol_bytes + 1 > len(data): raise ID3JunkFrameError shift = ((8 - (bits & 7)) & 7) + (4 - vol_bytes) * 8 for i in range(1, vol_bytes+1): peak *= 256 peak += data_array[i] peak *= 2 ** shift return (float(peak) / (2**31-1)), data[1+vol_bytes:] def write(self, frame, value): number = int(round(value * 32768)) # pack only fails in 2.7, do it manually in 2.6 if not 0 <= number <= 65535: raise struct.error # always write as 16 bits for sanity. return b"\x10" + pack('>H', number) def validate(self, frame, value): if value is not None: try: self.write(frame, value) except struct.error: raise ValueError("out of range") return value
class VolumePeakSpec(Spec): def read(self, frame, data): pass def write(self, frame, value): pass def validate(self, frame, value): pass
4
0
10
1
8
1
3
0.15
1
6
1
0
3
0
3
6
34
4
26
11
22
4
26
11
22
3
2
2
8
146,936
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.Frame
class Frame(object): """Fundamental unit of ID3 data. ID3 tags are split into frames. Each frame has a potentially different structure, and so this base class is not very featureful. """ FLAG23_ALTERTAG = 0x8000 FLAG23_ALTERFILE = 0x4000 FLAG23_READONLY = 0x2000 FLAG23_COMPRESS = 0x0080 FLAG23_ENCRYPT = 0x0040 FLAG23_GROUP = 0x0020 FLAG24_ALTERTAG = 0x4000 FLAG24_ALTERFILE = 0x2000 FLAG24_READONLY = 0x1000 FLAG24_GROUPID = 0x0040 FLAG24_COMPRESS = 0x0008 FLAG24_ENCRYPT = 0x0004 FLAG24_UNSYNCH = 0x0002 FLAG24_DATALEN = 0x0001 _framespec = [] def __init__(self, *args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and \ isinstance(args[0], type(self)): other = args[0] for checker in self._framespec: try: val = checker.validate(self, getattr(other, checker.name)) except ValueError as e: raise ValueError("%s: %s" % (checker.name, str(e))) setattr(self, checker.name, val) else: for checker, val in zip(self._framespec, args): setattr(self, checker.name, checker.validate(self, val)) for checker in self._framespec[len(args):]: try: validated = checker.validate( self, kwargs.get(checker.name, None)) except ValueError as e: raise ValueError("%s: %s" % (checker.name, str(e))) setattr(self, checker.name, validated) def _get_v23_frame(self, **kwargs): """Returns a frame copy which is suitable for writing into a v2.3 tag. kwargs get passed to the specs. """ new_kwargs = {} for checker in self._framespec: name = checker.name value = getattr(self, name) new_kwargs[name] = checker._validate23(self, value, **kwargs) return type(self)(**new_kwargs) @property def HashKey(self): """An internal key used to ensure frame uniqueness in a tag""" return self.FrameID @property def FrameID(self): """ID3v2 three or four character frame ID""" return type(self).__name__ def __repr__(self): """Python representation of a frame. The string returned is a valid Python expression to construct a copy of this frame. """ kw = [] for attr in self._framespec: kw.append('%s=%r' % (attr.name, getattr(self, attr.name))) return '%s(%s)' % (type(self).__name__, ', '.join(kw)) def _readData(self, data): odata = data for reader in self._framespec: if len(data): try: value, data = reader.read(self, data) except UnicodeDecodeError: raise ID3JunkFrameError else: raise ID3JunkFrameError setattr(self, reader.name, value) if data.strip(b'\x00'): warn('Leftover data: %s: %r (from %r)' % ( type(self).__name__, data, odata), ID3Warning) def _writeData(self): data = [] for writer in self._framespec: data.append(writer.write(self, getattr(self, writer.name))) return b''.join(data) def pprint(self): """Return a human-readable representation of the frame.""" return "%s=%s" % (type(self).__name__, self._pprint()) def _pprint(self): return "[unrepresentable data]" @classmethod def fromData(cls, id3, tflags, data): """Construct this ID3 frame from raw string data.""" if id3._V24 <= id3.version: if tflags & (Frame.FLAG24_COMPRESS | Frame.FLAG24_DATALEN): # The data length int is syncsafe in 2.4 (but not 2.3). # However, we don't actually need the data length int, # except to work around a QL 0.12 bug, and in that case # all we need are the raw bytes. datalen_bytes = data[:4] data = data[4:] if tflags & Frame.FLAG24_UNSYNCH or id3.f_unsynch: try: data = unsynch.decode(data) except ValueError as err: if id3.PEDANTIC: raise ID3BadUnsynchData('%s: %r' % (err, data)) if tflags & Frame.FLAG24_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG24_COMPRESS: try: data = zlib.decompress(data) except zlib.error as err: # the initial mutagen that went out with QL 0.12 did not # write the 4 bytes of uncompressed size. Compensate. data = datalen_bytes + data try: data = zlib.decompress(data) except zlib.error as err: if id3.PEDANTIC: raise ID3BadCompressedData('%s: %r' % (err, data)) elif id3._V23 <= id3.version: if tflags & Frame.FLAG23_COMPRESS: usize, = unpack('>L', data[:4]) data = data[4:] if tflags & Frame.FLAG23_ENCRYPT: raise ID3EncryptionUnsupportedError if tflags & Frame.FLAG23_COMPRESS: try: data = zlib.decompress(data) except zlib.error as err: if id3.PEDANTIC: raise ID3BadCompressedData('%s: %r' % (err, data)) frame = cls() frame._rawdata = data frame._flags = tflags frame._readData(data) return frame def __hash__(self): raise TypeError("Frame objects are unhashable") def __str__(self): return u"No tag-specific string/unicode representation for " + type(self).__name__ def __bytes__(self): return b"No tag-specific bytes representation for " + type(self).__name__.encode('utf-8')
class Frame(object): '''Fundamental unit of ID3 data. ID3 tags are split into frames. Each frame has a potentially different structure, and so this base class is not very featureful. ''' def __init__(self, *args, **kwargs): pass def _get_v23_frame(self, **kwargs): '''Returns a frame copy which is suitable for writing into a v2.3 tag. kwargs get passed to the specs. ''' pass @property def HashKey(self): '''An internal key used to ensure frame uniqueness in a tag''' pass @property def FrameID(self): '''ID3v2 three or four character frame ID''' pass def __repr__(self): '''Python representation of a frame. The string returned is a valid Python expression to construct a copy of this frame. ''' pass def _readData(self, data): pass def _writeData(self): pass def pprint(self): '''Return a human-readable representation of the frame.''' pass def _pprint(self): pass @classmethod def fromData(cls, id3, tflags, data): '''Construct this ID3 frame from raw string data.''' pass def __hash__(self): pass def __str__(self): pass def __bytes__(self): pass
17
7
10
1
8
1
3
0.17
1
13
6
26
12
0
13
13
171
25
125
52
108
21
115
47
101
17
1
5
42
146,937
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_tools_moggsplit.py
tests.test_tools_moggsplit.TMOggSPlit
class TMOggSPlit(_TTools): TOOL_NAME = 'moggsplit' def setUp(self): super(TMOggSPlit, self).setUp() original = os.path.join('tests', 'data', 'multipagecomment.ogg') fd, self.filename = mkstemp(suffix='.ogg') os.close(fd) shutil.copy(original, self.filename) # append the second file first = open(self.filename, 'ab') to_append = os.path.join('tests', 'data', 'multipage-setup.ogg') second = open(to_append, 'rb') first.write(second.read()) second.close() first.close() def tearDown(self): super(TMOggSPlit, self).tearDown() os.unlink(self.filename) def test_basic(self): d = os.path.dirname(self.filename) p = os.path.join(d, '%(stream)d.%(ext)s') res, out = self.call('--pattern', p, self.filename) self.failIf(res) self.failIf(out) for stream in [1002429366, 1806412655]: stream_path = os.path.join(d, str(stream) + '.ogg') self.failUnless(os.path.exists(stream_path)) os.unlink(stream_path)
class TMOggSPlit(_TTools): def setUp(self): pass def tearDown(self): pass def test_basic(self): pass
4
0
9
1
8
0
1
0.04
1
2
0
0
3
1
3
82
34
6
27
15
23
1
27
15
23
2
4
1
4
146,938
LordSputnik/mutagen
LordSputnik_mutagen/tests/test_tools_mutagen_inspect.py
tests.test_tools_mutagen_inspect.TMutagenInspect
class TMutagenInspect(_TTools): TOOL_NAME = 'mutagen-inspect' def test_basic(self): base = os.path.join('tests', 'data') self.paths = glob.glob(os.path.join(base, 'empty*')) self.paths += glob.glob(os.path.join(base, 'silence-*')) for path in self.paths: res, out = self.call(path) self.failIf(res) self.failUnless(out.strip()) self.failIf("Unknown file type" in out) self.failIf("Errno" in out)
class TMutagenInspect(_TTools): def test_basic(self): pass
2
0
11
1
10
0
2
0
1
0
0
0
1
1
1
80
15
3
12
7
10
0
12
7
10
2
4
1
2
146,939
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.ETCO
class ETCO(Frame): """Event timing codes.""" _framespec = [ ByteSpec("format"), KeyEventSpec("events"), ] def __eq__(self, other): return self.events == other __hash__ = Frame.__hash__
class ETCO(Frame): '''Event timing codes.''' def __eq__(self, other): pass
2
1
2
0
2
0
1
0.13
1
0
0
1
1
0
1
14
12
3
8
4
6
1
5
4
3
1
2
0
1
146,940
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.EQU2
class EQU2(Frame): """Equalisation (2). Attributes: method -- interpolation method (0 = band, 1 = linear) desc -- identifying description adjustments -- list of (frequency, vol_adjustment) pairs """ _framespec = [ ByteSpec("method"), Latin1TextSpec("desc"), VolumeAdjustmentsSpec("adjustments"), ] def __eq__(self, other): return self.adjustments == other __hash__ = Frame.__hash__ @property def HashKey(self): return '%s:%s' % (self.FrameID, self.desc)
class EQU2(Frame): '''Equalisation (2). Attributes: method -- interpolation method (0 = band, 1 = linear) desc -- identifying description adjustments -- list of (frequency, vol_adjustment) pairs ''' def __eq__(self, other): pass @property def HashKey(self): pass
4
1
2
0
2
0
1
0.5
1
0
0
0
2
0
2
15
23
5
12
6
8
6
7
5
4
1
2
0
2
146,941
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/_id3frames.py
mutagen._id3frames.ENCR
class ENCR(Frame): """Encryption method registration. The standard does not allow multiple ENCR frames with the same owner or the same method. Mutagen only verifies that the owner is unique. """ _framespec = [ Latin1TextSpec('owner'), ByteSpec('method'), BinaryDataSpec('data'), ] @property def HashKey(self): return "%s:%s" % (self.FrameID, self.owner) def __bytes__(self): return self.data def __eq__(self, other): return self.data == other __hash__ = Frame.__hash__
class ENCR(Frame): '''Encryption method registration. The standard does not allow multiple ENCR frames with the same owner or the same method. Mutagen only verifies that the owner is unique. ''' @property def HashKey(self): pass def __bytes__(self): pass def __eq__(self, other): pass
5
1
2
0
2
0
1
0.29
1
0
0
0
3
0
3
16
24
6
14
7
9
4
9
6
5
1
2
0
3
146,942
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/oggflac.py
mutagen.oggflac.OggFLAC
class OggFLAC(OggFileType): """An Ogg FLAC file.""" _Info = OggFLACStreamInfo _Tags = OggFLACVComment _Error = OggFLACHeaderError _mimes = ["audio/x-oggflac"] @staticmethod def score(filename, fileobj, header): return (header.startswith(b"OggS") * ( (b"FLAC" in header) + (b"fLaC" in header)))
class OggFLAC(OggFileType): '''An Ogg FLAC file.''' @staticmethod def score(filename, fileobj, header): pass
3
1
3
0
3
0
1
0.11
1
0
0
0
0
0
1
17
12
2
9
7
6
1
7
6
5
1
3
0
1
146,943
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/ogg.py
mutagen.ogg.error
class error(IOError): """Ogg stream parsing errors.""" pass
class error(IOError): '''Ogg stream parsing errors.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
5
0
0
0
0
4
1
2
1
1
1
2
1
1
0
1
0
0
146,944
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/ogg.py
mutagen.ogg.OggPage
class OggPage(object): """A single Ogg page (not necessarily a single encoded packet). A page is a header of 26 bytes, followed by the length of the data, followed by the data. The constructor is givin a file-like object pointing to the start of an Ogg page. After the constructor is finished it is pointing to the start of the next page. Attributes: * version -- stream structure version (currently always 0) * position -- absolute stream position (default -1) * serial -- logical stream serial number (default 0) * sequence -- page sequence number within logical stream (default 0) * offset -- offset this page was read from (default None) * complete -- if the last packet on this page is complete (default True) * packets -- list of raw packet data (default []) Note that if 'complete' is false, the next page's 'continued' property must be true (so set both when constructing pages). If a file-like object is supplied to the constructor, the above attributes will be filled in based on it. """ version = 0 __type_flags = 0 position = 0 serial = 0 sequence = 0 offset = None complete = True def __init__(self, fileobj=None): self.packets = [] if fileobj is None: return self.offset = fileobj.tell() header = fileobj.read(27) if len(header) == 0: raise EOFError try: (oggs, self.version, self.__type_flags, self.position, self.serial, self.sequence, crc, segments) = struct.unpack( "<4sBBqIIiB", header) except struct.error: raise error("unable to read full header; got %r" % header) if oggs != b"OggS": raise error("read %r, expected %r, at 0x%x" % ( oggs, b"OggS", fileobj.tell() - 27)) if self.version != 0: raise error("version %r unsupported" % self.version) total = 0 lacings = [] lacing_bytes = fileobj.read(segments) if len(lacing_bytes) != segments: raise error("unable to read %r lacing bytes" % segments) for c in bytearray(lacing_bytes): total += c if c < 255: lacings.append(total) total = 0 if total: lacings.append(total) self.complete = False self.packets = [fileobj.read(l) for l in lacings] if list(map(len, self.packets)) != lacings: raise error("unable to read full data") def __eq__(self, other): """Two Ogg pages are the same if they write the same data.""" try: return (self.write() == other.write()) except AttributeError: return False __hash__ = object.__hash__ def __repr__(self): attrs = ['version', 'position', 'serial', 'sequence', 'offset', 'complete', 'continued', 'first', 'last'] values = ["%s=%r" % (attr, getattr(self, attr)) for attr in attrs] return "<%s %s, %d bytes in %d packets>" % ( type(self).__name__, " ".join(values), sum(map(len, self.packets)), len(self.packets)) def write(self): """Return a string encoding of the page header and data. A ValueError is raised if the data is too big to fit in a single page. """ data = [ struct.pack("<4sBBqIIi", b"OggS", self.version, self.__type_flags, self.position, self.serial, self.sequence, 0) ] lacing_data = [] for datum in self.packets: quot, rem = divmod(len(datum), 255) lacing_data.append(b"\xff" * quot + chr_(rem)) lacing_data = b"".join(lacing_data) if not self.complete and lacing_data.endswith(b"\x00"): lacing_data = lacing_data[:-1] data.append(chr_(len(lacing_data))) data.append(lacing_data) data.extend(self.packets) data = b"".join(data) # Python's CRC is swapped relative to Ogg's needs. # crc32 returns uint prior to py2.6 on some platforms, so force uint crc = (~zlib.crc32(data.translate(cdata.bitswap), -1)) & 0xffffffff # Although we're using to_uint_be, this actually makes the CRC # a proper le integer, since Python's CRC is byteswapped. crc = cdata.to_uint_be(crc).translate(cdata.bitswap) data = data[:22] + crc + data[26:] return data @property def size(self): """Total frame size.""" header_size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) header_size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is not # terminated, so we don't have a \x00 at the end. header_size -= 1 header_size += sum(map(len, self.packets)) return header_size def __set_flag(self, bit, val): mask = 1 << bit if val: self.__type_flags |= mask else: self.__type_flags &= ~mask continued = property( lambda self: cdata.test_bit(self.__type_flags, 0), lambda self, v: self.__set_flag(0, v), doc="The first packet is continued from the previous page.") first = property( lambda self: cdata.test_bit(self.__type_flags, 1), lambda self, v: self.__set_flag(1, v), doc="This is the first page of a logical bitstream.") last = property( lambda self: cdata.test_bit(self.__type_flags, 2), lambda self, v: self.__set_flag(2, v), doc="This is the last page of a logical bitstream.") @staticmethod def renumber(fileobj, serial, start): """Renumber pages belonging to a specified logical stream. fileobj must be opened with mode r+b or w+b. Starting at page number 'start', renumber all pages belonging to logical stream 'serial'. Other pages will be ignored. fileobj must point to the start of a valid Ogg page; any occuring after it and part of the specified logical stream will be numbered. No adjustment will be made to the data in the pages nor the granule position; only the page number, and so also the CRC. If an error occurs (e.g. non-Ogg data is found), fileobj will be left pointing to the place in the stream the error occured, but the invalid data will be left intact (since this function does not change the total file size). """ number = start while True: try: page = OggPage(fileobj) except EOFError: break else: if page.serial != serial: # Wrong stream, skip this page. continue # Changing the number can't change the page size, # so seeking back based on the current size is safe. fileobj.seek(-page.size, 1) page.sequence = number fileobj.write(page.write()) fileobj.seek(page.offset + page.size, 0) number += 1 @staticmethod def to_packets(pages, strict=False): """Construct a list of packet data from a list of Ogg pages. If strict is true, the first page must start a new packet, and the last page must end the last packet. """ serial = pages[0].serial sequence = pages[0].sequence packets = [] if strict: if pages[0].continued: raise ValueError("first packet is continued") if not pages[-1].complete: raise ValueError("last packet does not complete") elif pages and pages[0].continued: packets.append([b""]) for page in pages: if serial != page.serial: raise ValueError("invalid serial number in %r" % page) elif sequence != page.sequence: raise ValueError("bad sequence number in %r" % page) else: sequence += 1 if page.continued: packets[-1].append(page.packets[0]) else: packets.append([page.packets[0]]) packets.extend([p] for p in page.packets[1:]) return [b"".join(p) for p in packets] @staticmethod def from_packets(packets, sequence=0, default_size=4096, wiggle_room=2048): """Construct a list of Ogg pages from a list of packet data. The algorithm will generate pages of approximately default_size in size (rounded down to the nearest multiple of 255). However, it will also allow pages to increase to approximately default_size + wiggle_room if allowing the wiggle room would finish a packet (only one packet will be finished in this way per page; if the next packet would fit into the wiggle room, it still starts on a new page). This method reduces packet fragmentation when packet sizes are slightly larger than the default page size, while still ensuring most pages are of the average size. Pages are numbered started at 'sequence'; other information is uninitialized. """ chunk_size = (default_size // 255) * 255 pages = [] page = OggPage() page.sequence = sequence for packet in packets: page.packets.append(b"") while packet: data, packet = packet[:chunk_size], packet[chunk_size:] if page.size < default_size and len(page.packets) < 255: page.packets[-1] += data else: # If we've put any packet data into this page yet, # we need to mark it incomplete. However, we can # also have just started this packet on an already # full page, in which case, just start the new # page with this packet. if page.packets[-1]: page.complete = False if len(page.packets) == 1: page.position = -1 else: page.packets.pop(-1) pages.append(page) page = OggPage() page.continued = not pages[-1].complete page.sequence = pages[-1].sequence + 1 page.packets.append(data) if len(packet) < wiggle_room: page.packets[-1] += packet packet = b"" if page.packets: pages.append(page) return pages @classmethod def replace(cls, fileobj, old_pages, new_pages): """Replace old_pages with new_pages within fileobj. old_pages must have come from reading fileobj originally. new_pages are assumed to have the 'same' data as old_pages, and so the serial and sequence numbers will be copied, as will the flags for the first and last pages. fileobj will be resized and pages renumbered as necessary. As such, it must be opened r+b or w+b. """ # Number the new pages starting from the first old page. first = old_pages[0].sequence for page, seq in zip(new_pages, range(first, first + len(new_pages))): page.sequence = seq page.serial = old_pages[0].serial new_pages[0].first = old_pages[0].first new_pages[0].last = old_pages[0].last new_pages[0].continued = old_pages[0].continued new_pages[-1].first = old_pages[-1].first new_pages[-1].last = old_pages[-1].last new_pages[-1].complete = old_pages[-1].complete if not new_pages[-1].complete and len(new_pages[-1].packets) == 1: new_pages[-1].position = -1 new_data = b''.join(cls.write(p) for p in new_pages) # Make room in the file for the new data. delta = len(new_data) fileobj.seek(old_pages[0].offset, 0) insert_bytes(fileobj, delta, old_pages[0].offset) fileobj.seek(old_pages[0].offset, 0) fileobj.write(new_data) new_data_end = old_pages[0].offset + delta # Go through the old pages and delete them. Since we shifted # the data down the file, we need to adjust their offsets. We # also need to go backwards, so we don't adjust the deltas of # the other pages. old_pages.reverse() for old_page in old_pages: adj_offset = old_page.offset + delta delete_bytes(fileobj, old_page.size, adj_offset) # Finally, if there's any discrepency in length, we need to # renumber the pages for the logical stream. if len(old_pages) != len(new_pages): fileobj.seek(new_data_end, 0) serial = new_pages[-1].serial sequence = new_pages[-1].sequence + 1 cls.renumber(fileobj, serial, sequence) @staticmethod def find_last(fileobj, serial): """Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), whichever comes first. """ # For non-muxed streams, look at the last page. try: fileobj.seek(-256*256, 2) except IOError: # The file is less than 64k in length. fileobj.seek(0) data = fileobj.read() try: index = data.rindex(b"OggS") except ValueError: raise error("unable to find final Ogg header") bytesobj = cBytesIO(data[index:]) best_page = None try: page = OggPage(bytesobj) except error: pass else: if page.serial == serial: if page.last: return page else: best_page = page else: best_page = None # The stream is muxed, so use the slow way. fileobj.seek(0) try: page = OggPage(fileobj) while not page.last: page = OggPage(fileobj) while page.serial != serial: page = OggPage(fileobj) best_page = page return page except error: return best_page except EOFError: return best_page
class OggPage(object): '''A single Ogg page (not necessarily a single encoded packet). A page is a header of 26 bytes, followed by the length of the data, followed by the data. The constructor is givin a file-like object pointing to the start of an Ogg page. After the constructor is finished it is pointing to the start of the next page. Attributes: * version -- stream structure version (currently always 0) * position -- absolute stream position (default -1) * serial -- logical stream serial number (default 0) * sequence -- page sequence number within logical stream (default 0) * offset -- offset this page was read from (default None) * complete -- if the last packet on this page is complete (default True) * packets -- list of raw packet data (default []) Note that if 'complete' is false, the next page's 'continued' property must be true (so set both when constructing pages). If a file-like object is supplied to the constructor, the above attributes will be filled in based on it. ''' def __init__(self, fileobj=None): pass def __eq__(self, other): '''Two Ogg pages are the same if they write the same data.''' pass def __repr__(self): pass def write(self): '''Return a string encoding of the page header and data. A ValueError is raised if the data is too big to fit in a single page. ''' pass @property def size(self): '''Total frame size.''' pass def __set_flag(self, bit, val): pass @staticmethod def renumber(fileobj, serial, start): '''Renumber pages belonging to a specified logical stream. fileobj must be opened with mode r+b or w+b. Starting at page number 'start', renumber all pages belonging to logical stream 'serial'. Other pages will be ignored. fileobj must point to the start of a valid Ogg page; any occuring after it and part of the specified logical stream will be numbered. No adjustment will be made to the data in the pages nor the granule position; only the page number, and so also the CRC. If an error occurs (e.g. non-Ogg data is found), fileobj will be left pointing to the place in the stream the error occured, but the invalid data will be left intact (since this function does not change the total file size). ''' pass @staticmethod def to_packets(pages, strict=False): '''Construct a list of packet data from a list of Ogg pages. If strict is true, the first page must start a new packet, and the last page must end the last packet. ''' pass @staticmethod def from_packets(packets, sequence=0, default_size=4096, wiggle_room=2048): '''Construct a list of Ogg pages from a list of packet data. The algorithm will generate pages of approximately default_size in size (rounded down to the nearest multiple of 255). However, it will also allow pages to increase to approximately default_size + wiggle_room if allowing the wiggle room would finish a packet (only one packet will be finished in this way per page; if the next packet would fit into the wiggle room, it still starts on a new page). This method reduces packet fragmentation when packet sizes are slightly larger than the default page size, while still ensuring most pages are of the average size. Pages are numbered started at 'sequence'; other information is uninitialized. ''' pass @classmethod def replace(cls, fileobj, old_pages, new_pages): '''Replace old_pages with new_pages within fileobj. old_pages must have come from reading fileobj originally. new_pages are assumed to have the 'same' data as old_pages, and so the serial and sequence numbers will be copied, as will the flags for the first and last pages. fileobj will be resized and pages renumbered as necessary. As such, it must be opened r+b or w+b. ''' pass @staticmethod def find_last(fileobj, serial): '''Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), whichever comes first. ''' pass
18
9
31
4
20
7
5
0.4
1
11
2
0
6
1
11
11
409
69
244
74
225
97
210
66
198
11
1
5
58
146,945
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/ogg.py
mutagen.ogg.OggFileType
class OggFileType(FileType): """An generic Ogg file.""" _Info = None _Tags = None _Error = None _mimes = ["application/ogg", "application/x-ogg"] def load(self, filename): """Load file information from a filename.""" self.filename = filename fileobj = open(filename, "rb") try: try: self.info = self._Info(fileobj) self.tags = self._Tags(fileobj, self.info) self.info._post_tags(fileobj) except error as e: reraise(self._Error, e, sys.exc_info()[2]) except EOFError: raise self._Error("no appropriate stream found") finally: fileobj.close() def delete(self, filename=None): """Remove tags from a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename self.tags.clear() fileobj = open(filename, "rb+") try: try: self.tags._inject(fileobj) except error as e: reraise(self._Error, e, sys.exc_info()[2]) except EOFError: raise self._Error("no appropriate stream found") finally: fileobj.close() def save(self, filename=None): """Save a tag to a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename fileobj = open(filename, "rb+") try: try: self.tags._inject(fileobj) except error as e: reraise(self._Error, e, sys.exc_info()[2]) except EOFError: raise self._Error("no appropriate stream found") finally: fileobj.close()
class OggFileType(FileType): '''An generic Ogg file.''' def load(self, filename): '''Load file information from a filename.''' pass def delete(self, filename=None): '''Remove tags from a file. If no filename is given, the one most recently loaded is used. ''' pass def save(self, filename=None): '''Save a tag to a file. If no filename is given, the one most recently loaded is used. ''' pass
4
4
18
2
14
2
4
0.17
1
2
1
5
3
3
3
16
64
10
46
17
42
8
43
14
39
4
2
2
11
146,946
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/musepack.py
mutagen.musepack.MusepackInfo
class MusepackInfo(StreamInfo): """Musepack stream information. Attributes: * channels -- number of audio channels * length -- file length in seconds, as a float * sample_rate -- audio sampling rate in Hz * bitrate -- audio bitrate, in bits per second * version -- Musepack stream version Optional Attributes: * title_gain, title_peak -- Replay Gain and peak data for this song * album_gain, album_peak -- Replay Gain and peak data for this album These attributes are only available in stream version 7/8. The gains are a float, +/- some dB. The peaks are a percentage [0..1] of the maximum amplitude. This means to get a number comparable to VorbisGain, you must multiply the peak by 2. """ def __init__(self, fileobj): header = fileobj.read(4) if len(header) != 4: raise MusepackHeaderError("not a Musepack file") # Skip ID3v2 tags if header[:3] == b"ID3": header = fileobj.read(6) if len(header) != 6: raise MusepackHeaderError("not a Musepack file") size = 10 + BitPaddedInt(header[2:6]) fileobj.seek(size) header = fileobj.read(4) if len(header) != 4: raise MusepackHeaderError("not a Musepack file") if header.startswith(b"MPCK"): self.__parse_sv8(fileobj) else: self.__parse_sv467(fileobj) if not self.bitrate and self.length != 0: fileobj.seek(0, 2) self.bitrate = int(round(fileobj.tell() * 8 / self.length)) def __parse_sv8(self, fileobj): #SV8 http://trac.musepack.net/trac/wiki/SV8Specification key_size = 2 mandatory_packets = [b"SH", b"RG"] def check_frame_key(key): if (len(frame_type) != key_size) or (not b'AA' <= frame_type <= b'ZZ'): raise MusepackHeaderError("Invalid frame key.") frame_type = fileobj.read(key_size) check_frame_key(frame_type) while frame_type not in (b"AP", b"SE") and mandatory_packets: try: frame_size, slen = _parse_sv8_int(fileobj) except (EOFError, ValueError): raise MusepackHeaderError("Invalid packet size.") data_size = frame_size - key_size - slen if frame_type == b"SH": mandatory_packets.remove(frame_type) self.__parse_stream_header(fileobj, data_size) elif frame_type == b"RG": mandatory_packets.remove(frame_type) self.__parse_replaygain_packet(fileobj, data_size) else: fileobj.seek(data_size, 1) frame_type = fileobj.read(key_size) check_frame_key(frame_type) if mandatory_packets: raise MusepackHeaderError("Missing mandatory packets: %s." % ", ".join(map(repr, mandatory_packets))) self.length = float(self.samples) / self.sample_rate self.bitrate = 0 def __parse_stream_header(self, fileobj, data_size): fileobj.seek(4, 1) try: self.version = ord_(fileobj.read(1)) except TypeError: raise MusepackHeaderError("SH packet ended unexpectedly.") try: samples, l1 = _parse_sv8_int(fileobj) samples_skip, l2 = _parse_sv8_int(fileobj) except (EOFError, ValueError): raise MusepackHeaderError( "SH packet: Invalid sample counts.") left_size = data_size - 5 - l1 - l2 if left_size != 2: raise MusepackHeaderError("Invalid SH packet size.") data = fileobj.read(left_size) if len(data) != left_size: raise MusepackHeaderError("SH packet ended unexpectedly.") self.sample_rate = RATES[ord_(data[-2:-1]) >> 5] self.channels = (ord_(data[-1:]) >> 4) + 1 self.samples = samples - samples_skip def __parse_replaygain_packet(self, fileobj, data_size): data = fileobj.read(data_size) if data_size != 9: raise MusepackHeaderError("Invalid RG packet size.") if len(data) != data_size: raise MusepackHeaderError("RG packet ended unexpectedly.") title_gain = cdata.short_be(data[1:3]) title_peak = cdata.short_be(data[3:5]) album_gain = cdata.short_be(data[5:7]) album_peak = cdata.short_be(data[7:9]) if title_gain: self.title_gain = _calc_sv8_gain(title_gain) if title_peak: self.title_peak = _calc_sv8_peak(title_peak) if album_gain: self.album_gain = _calc_sv8_gain(album_gain) if album_peak: self.album_peak = _calc_sv8_peak(album_peak) def __parse_sv467(self, fileobj): fileobj.seek(-4, 1) header = fileobj.read(32) if len(header) != 32: raise MusepackHeaderError("not a Musepack file") # SV7 if header.startswith(b"MP+"): self.version = ord_(header[3:4]) & 0xF if self.version < 7: raise MusepackHeaderError("not a Musepack file") frames = cdata.uint_le(header[4:8]) flags = cdata.uint_le(header[8:12]) self.title_peak, self.title_gain = struct.unpack( "<Hh", header[12:16]) self.album_peak, self.album_gain = struct.unpack( "<Hh", header[16:20]) self.title_gain /= 100.0 self.album_gain /= 100.0 self.title_peak /= 65535.0 self.album_peak /= 65535.0 self.sample_rate = RATES[(flags >> 16) & 0x0003] self.bitrate = 0 # SV4-SV6 else: header_dword = cdata.uint_le(header[0:4]) self.version = (header_dword >> 11) & 0x03FF if self.version < 4 or self.version > 6: raise MusepackHeaderError("not a Musepack file") self.bitrate = (header_dword >> 23) & 0x01FF self.sample_rate = 44100 if self.version >= 5: frames = cdata.uint_le(header[4:8]) else: frames = cdata.ushort_le(header[6:8]) if self.version < 6: frames -= 1 self.channels = 2 self.length = float(frames * 1152 - 576) / self.sample_rate def pprint(self): rg_data = [] if hasattr(self, "title_gain"): rg_data.append("%+0.2f (title)" % self.title_gain) if hasattr(self, "album_gain"): rg_data.append("%+0.2f (album)" % self.album_gain) rg_data = (rg_data and ", Gain: " + ", ".join(rg_data)) or "" return "Musepack SV%d, %.2f seconds, %d Hz, %d bps%s" % ( self.version, self.length, self.sample_rate, self.bitrate, rg_data)
class MusepackInfo(StreamInfo): '''Musepack stream information. Attributes: * channels -- number of audio channels * length -- file length in seconds, as a float * sample_rate -- audio sampling rate in Hz * bitrate -- audio bitrate, in bits per second * version -- Musepack stream version Optional Attributes: * title_gain, title_peak -- Replay Gain and peak data for this song * album_gain, album_peak -- Replay Gain and peak data for this album These attributes are only available in stream version 7/8. The gains are a float, +/- some dB. The peaks are a percentage [0..1] of the maximum amplitude. This means to get a number comparable to VorbisGain, you must multiply the peak by 2. ''' def __init__(self, fileobj): pass def __parse_sv8(self, fileobj): pass def check_frame_key(key): pass def __parse_stream_header(self, fileobj, data_size): pass def __parse_replaygain_packet(self, fileobj, data_size): pass def __parse_sv467(self, fileobj): pass def pprint(self): pass
8
1
22
2
19
1
5
0.14
1
9
3
0
6
10
6
7
179
26
134
39
126
19
124
39
116
7
2
2
37
146,947
LordSputnik/mutagen
LordSputnik_mutagen/mutagen/musepack.py
mutagen.musepack.Musepack
class Musepack(APEv2File): _Info = MusepackInfo _mimes = ["audio/x-musepack", "audio/x-mpc"] @staticmethod def score(filename, fileobj, header): filename = filename.lower() return (header.startswith(b"MP+") + header.startswith(b"MPCK") + endswith(filename, b".mpc"))
class Musepack(APEv2File): @staticmethod def score(filename, fileobj, header): pass
3
0
5
1
4
0
1
0
1
0
0
0
0
0
1
17
10
2
8
5
5
0
6
4
4
1
3
0
1