2017-08-07 11 views
2

ユニットテストケースを記述しています。私は、ファイルオブジェクトを作成し、それを読んで、私は次のエラーを取得しています:ファイルを読み込み中に<<: 'str'と 'int'のサポートされないオペランドタイプ

unsupported operand type(s) for <<: 'str' and 'int'

方法:

def uploadExamineeDetails(request, exam_id): 
    try: 
     upload_file = request.FILES['upload-file'] 
    except Exception: 
     return [_('Uploaded file is required.')] 
    try: 
     exam = get_object_or_404_from_admin(CourseExam, request, exam_id) 
     book = xlrd.open_workbook(file_contents=upload_file.read()) 
     # further code 

私のテストコード:Excelファイル内

def test_uploadExamineeDetails(self): 

    self.examinee_result = os.path.join(os.path.dirname(settings.BASE_DIR),\ 
             'var/sample_files_for_testing/examinees_result_upload.xls') 
    file = File(open(self.file, errors='ignore')) 
    uploaded_file = InMemoryUploadedFile(file=file, field_name='upload-file', name='examinee_result.xls', 
             content_type = 'application/vnd.ms-excel', size = file.size, charset = None) 
    self.request.FILES['upload-file'] = uploaded_file 
    xlrd.open_workbook(file_contents=uploaded_file.read()) 
    response = uploadExamineeDetails(self.request, 1) 
    assert isinstance(response, tuple), 'should upload the examinee details' 

データ:

[{'Enrollment Number': '', 'Username': 'exam_course_manager', 
'row_num': 1, 'Obtained Score': 60.0, 'GR Number': ''}, 
{'Enrollment Number': '', 'Username': 'instructor', 
'row_num': 2, 'Obtained Score': 20.0, 'GR Number': ''}] 

トレースバック:

 (py_3.5_dj_1.9) [email protected]:~/Projects/DROANA_3.0/droana/droana$ py.test droana/apps/course_planner/tests/test_methods.py 
============================= test session starts ============================== 
platform linux -- Python 3.5.2, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 
Django settings: droana.test_settings (from command line option) 
rootdir: /home/dikshaj/Projects/DROANA_3.0/droana/droana, inifile: pytest.ini 
plugins: django-3.1.2, cov-2.4.0, ipdb-0.1.dev2 
collected 1 items 

droana/apps/course_planner/tests/test_methods.py F 

----------- coverage: platform linux, python 3.5.2-final-0 ----------- 
Coverage HTML written to dir htmlcov 


=================================== FAILURES =================================== 
____________________ TestMethods.test_uploadExamineeDetails ____________________ 

self = <droana.apps.course_planner.tests.test_methods.TestMethods testMethod=test_uploadExamineeDetails> 

    def test_uploadExamineeDetails(self): 
     """ 
      Test uploadExamineeDetails method 
      """ 
     self.examinee_result = os.path.join(os.path.dirname(settings.BASE_DIR),\ 
              'var/sample_files_for_testing/examinees_result_upload.xls') 
     file = File(open(self.file, errors='ignore')) 
     uploaded_file = InMemoryUploadedFile(file=file, field_name='upload-file', name='examinee_result.xls', 
              content_type = 'application/vnd.ms-excel', size = file.size, charset = None) 
     self.request.FILES['upload-file'] = uploaded_file 
>  xlrd.open_workbook(file_contents=uploaded_file.read()) 

droana/apps/course_planner/tests/test_methods.py:100: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/opt/myvirtual/py_3.5_dj_1.9/lib/python3.5/site-packages/xlrd/__init__.py:435: in open_workbook 
    ragged_rows=ragged_rows, 
/opt/myvirtual/py_3.5_dj_1.9/lib/python3.5/site-packages/xlrd/book.py:91: in open_workbook_xls 
    biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) 
/opt/myvirtual/py_3.5_dj_1.9/lib/python3.5/site-packages/xlrd/book.py:1226: in getbof 
    opcode = self.get2bytes() 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <xlrd.book.Book object at 0x7fb57b458c88> 

    def get2bytes(self): 
     pos = self._position 
     buff_two = self.mem[pos:pos+2] 
     lenbuff = len(buff_two) 
     self._position += lenbuff 
     if lenbuff < 2: 
      return MY_EOF 
     lo, hi = buff_two 
>  return (BYTES_ORD(hi) << 8) | BYTES_ORD(lo) 
E  TypeError: unsupported operand type(s) for <<: 'str' and 'int' 

/opt/myvirtual/py_3.5_dj_1.9/lib/python3.5/site-packages/xlrd/book.py:631: TypeError 

このラインを読みながら、例外を投げるコード:

xlrd.open_workbook(file_contents=upload_file.read()) 

これは私がやっていることです。私はファイルを作成し、それをディレクトリに保存し、それを開いてコードで示すようにメモリ内のオブジェクトを作成します。エラーによると、私は文字列をintと比較しようとするとこのエラーが発生することに気付きました。しかし、私はなぜこれがファイルを読むことで起こっているのか分からない。

問題が何であるかは誰か知りませんか?

+2

質問に表示されているスタックトレースを含めることはできますか?それは価値があるため、あなたが表示したエラーメッセージには、ビットシフト演算子(<<)が含まれています。これはあなたのコードでは表示されませんので、使用しているライブラリコードの一部を投げかけていますエラー。スタックトレースは、どのパラメータが問題を引き起こす可能性があるかを絞り込むのに役立ちます。 –

+0

私はトレースバックを追加しましたが、同じ問題が依然として出ているtxtファイルをアップロードしても。私はファイルを読んでいる間に問題が発生していると思う。誰かが私にこの問題の解決策を与えることができれば、私は非常に感謝しています。 –

+0

xlrdの問題のように見えますが、私はオンラインで解決策を見つけることができず、そのライブラリに慣れていません。 'xlrd.open_workbook(file_contents = upload_file.read())'行を 'xlrd.open_workbook(filename = 'file-on-disk.xls')'行に変更すると、ファイルの内容を実際のファイルに保存すると、問題は解決しませんか? –

答えて

2

オープンバイナリモードでファイル:デフォルトでは

file = File(open(self.file, 'rb')) 

は、ファイルがUnicode文字(Pythonの3のタイプstr)のストリームとしてファイルを読み込みモード'r'、で開かれています。 xlrdのget2bytesメソッドは、'rb'モードでファイルを開くときに返されるバイトストリームを予期します。

この要件は、がfile_contentsの場合に実行されるxlrdによって間違って書かれているようです。コードにピアリング、BYTES_ORDdefined as the identity function on Python 3ので、file_contentsget2bytesに渡されるとき、strブロブは失敗'c'[0] << 8、をもたらすが、bytesbytesブロブがブロブの各要素がintあるため(成功b'c'[0] << 8、もたらします)。

+0

どうもありがとう。 –

関連する問題