I am getting an error in Python which goes like 'int' object not subscriptable error in JetBrains PyCharm

This is my code

def position_list(db,limit=10):
    """Return a list of positions ordered by date
    db is a database connection
    return at most limit positions (default 10)

    Returns a list of tuples  (id, timestamp, owner, title, location, company, description)
    """
    cursor = db.cursor()

    sql = "Select id, timestamp, owner, title,  description From positions order by timestamp desc limit 10"

    cursor.execute(sql)
    result =[]
    for row in cursor:
        result.append(row[0])
        result.append(row[1])
        result.append(row[2])
        result.append(row[3])
        result.append(row[4])

    return result

This is the test I have to pass:

    def test_position_list(self):
        """Test that position_list returns positions"""

        # first get all positions
        positions = interface.position_list(self.db, limit=1000)

        self.assertEqual(len(self.positions), len(positions))

        # validate the returned values

        self.assertEqual(1, positions[0][0])
        self.assertEqual('2018-03-07 22:36:19', positions[0][1])
        # can't check owner as it is randomly assigned
        self.assertEqual('Staff Site Reliability Engineer ', positions[0][3])

    def test_position_list_limit(self):
        """Test that position_list returns positions using the limit argument"""

        # now look at the limit argument
        positions = interface.position_list(self.db, limit=3)
        self.assertEqual(3, len(positions))

        positions = interface.position_list(self.db, limit=1)
        self.assertEqual(1, len(positions))

        # limit higher than number of positions
        positions = interface.position_list(self.db, limit=100)
        self.assertEqual(50, len(positions))

When I try to run the unit test I get

Type error: 'int' object is not subscriptable. 
This is due to the row[0] value of id which is an integer. 

How do I fix this?. Also can someone tell me how can I pass the def test_position_list_limit(self)?

1 answer

  • answered 2018-04-14 20:59 jpp

    Your position_list function needs to return a list of tuples. Returning a single list will guarantee that you fail both tests.

    Something like the below code should work.

    def position_list(db, limit=10):
    
        cursor = db.cursor()
        sql = "Select id, timestamp, owner, title,  description From positions order by timestamp desc limit 10"
        cursor.execute(sql)
    
        return [row for row in cursor]