我正在尝试运行一个python3单元测试脚本,但是当它使用来自主枕的对象并遇到导入语句时,它给了我一个模块未找到的错误。当我运行主脚本本身并按预期运行代码时,我不会遇到这个错误。我得到的错误跟踪是:
Traceback (most recent call last):
File "parkingLot_test.py", line 3, in <module>
from source import parking
File "/home/stash/Desktop/parking-lot/parking-lot-1.4.2/parking_lot/parking_lot/bin/source/parking.py", line 1, in <module>
import lot
ModuleNotFoundError: No module named 'lot'目录结构如下:
├── file_inputs.txt
├── parking_lot
├── parkingLot_test.py
├── run_functional_tests
├── setup
└── source
├── car.py
├── __init__.py
├── lot.py
├── main.py
├── parking.py单元测试文件parkingLot_test.py的代码
import unittest
from source import parking
class ParkingTest(unittest.TestCase):
@classmethod
def MakeClass(cls):
cls.parking = parking.Parking()
cls.allocated_slot = 1
def test_a_create_parking_lot(self):
parking_slots = 6
self.parking.create_parking_lot(parking_slots)
self.assertEqual(len(self.parking.slots), parking_slots,
msg="Wrong parking lot created")
def test_b_park(self):
registration_no = "MH-12-FF-2017"
colour = "Black"
self.parking.park(registration_no, colour)
self.assertFalse(
self.parking.slots[self.allocated_slot].available, "Park failed.")
for i in self.parking.slots.values():
if not i.available and i.car:
self.assertEqual(i.car.registration_no,
registration_no, "Park failed")
self.assertEqual(i.car.colour, colour, "Park failed")
def test_c_leave(self):
self.parking.leave(self.allocated_slot)
self.assertTrue(
self.parking.slots[self.allocated_slot].available, "Leave failed.")
@classmethod
def RemoveClass(cls):
del cls.parking
if __name__ == '__main__':
unittest.main()导入的文件parking.py的代码
import lot
import car
class Parking:
"""
Parking class which has details about parking slots
as well as operation performed on parking are present here
"""
def __init__(self):
self.slots = {}
def create_parking_lot(self, no_of_slots):
"""This method will create parking lot if not present already with given
number of slots.
Input: no_of_slots - Integer Type
"""
no_of_slots = int(no_of_slots)
if len(self.slots) > 0:
print("Parking Lot already created")
return
if no_of_slots > 0:
for i in range(1, no_of_slots+1):
temp_slot = lot.ParkingSlot(slotNum=i,
availability=True)
self.slots[i] = temp_slot
print("Created a parking lot with %s slots" % no_of_slots)
else:
print("Number of slots provided is incorrect.")
return
def get_nearest_available_slot(self):
...................我怎样才能解决这个问题?
发布于 2019-06-11 05:04:10
因为python 3不支持隐式相对导入。可以使用显式相对导入。
在parking.py中尝试使用下面的行来代替导入
from . import lot
发布于 2019-06-11 06:31:51
在同一个目录级别的文件中,当您在另一个目录中导入一个文件时,使用相对导入,如
在parking.py文件中,导入lot.py文件作为
import .log当从一个目录导入到较低目录(即导入parkingLot_test.py中的批量)时,请使用from source import lot
并在源文件夹中的__init__.py文件中写入
import .lot
import .parking就像这样。
https://stackoverflow.com/questions/56536673
复制相似问题