開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-12.を解いてみる。
12.7(練習問題)、12-12.
まず、python2.7のStringIOおよびcStringIOモジュールは、python3.xではioモジュールのStringIO classに変更されたみたい。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
import io
import nose
# ioモジュールのStringIOでは、文字列をファイルデータとして扱うことができる。
# よって、readlinesメソッド等を使うことが出来る。
def count_lines(a):
return len(a.readlines())
def test_zero_line():
s = io.StringIO('')
assert count_lines(s) == 0
def test_one_line():
s = io.StringIO('python')
assert count_lines(s) == 1
def test_two_lines():
s = io.StringIO('''python
haskell
''')
assert count_lines(s) == 2
def test_three_lines():
s = io.StringIO('''python
haskell
''')
assert count_lines(s) == 3
def test_four_lines():
s = io.StringIO('''
''')
assert count_lines(s) == 4
def test_five_lines():
s = io.StringIO('\n\n\n\n\n')
assert count_lines(s) == 5
if __name__ == '__main__':
nose.runmodule()
入出力結果(Terminal)
$ ./sample.py ...... ---------------------------------------------------------------------- Ran 6 tests in 0.002s OK $
0 コメント:
コメントを投稿