将具有多种职责的职能分解为多种职能

时间:2019-05-15 17:12:25

标签: python python-unittest

我正在上一门使用Python进行单元测试的课程,作为练习,他们希望我们使用一个函数,该函数读取页面并将其转换为html,然后将其拆分为两个单独的函数。这是html_pages.py的代码:


import html as html_converter


class FileAccessWrapper:
    def __init__(self, filename):
        self.filename = filename

    def open(self):
        return open(self.filename, "r", encoding="UTF-8")


class HtmlPagesConverter:

    def __init__(self, file_access):
        """Read the file and note the positions of the page breaks so we can access them quickly"""
        self.file_access = file_access
        self.breaks = [0]
        with self.file_access.open() as f:
            while True:
                line = f.readline()
                if not line:
                    break
                line = line.rstrip()
                if "PAGE_BREAK" in line:
                    page_break_position = f.tell()
                    self.breaks.append(f.tell())
            self.breaks.append(f.tell())                

    def get_html_page(self, page):
        """Return html page with the given number (zero indexed)"""
        page_start = self.breaks[page]
        page_end = self.breaks[page+1]
        html = ""
        with self.file_access.open() as f:
            f.seek(page_start)
            while f.tell() != page_end:
                line = f.readline()
                line = line.rstrip()
                if "PAGE_BREAK" in line:
                    continue
                html += html_converter.escape(line, quote=True)
                html += "<br />"
        return html

以下是他们在test_html_pages.py中定义的测试用例:

import unittest
import os
import tempfile
import io

from html_pages import HtmlPagesConverter, FileAccessWrapper


class HtmlPagesTest(unittest.TestCase):
    def test_inserts_br_tags_for_linebreaks(self):
        filename = os.path.join(tempfile.gettempdir(), "afile.txt")
        f = open(filename, "w", encoding="UTF-8")
        f.write("plain text\n")
        f.close()
        converter = HtmlPagesConverter(FileAccessWrapper(filename))
        new_text = converter.get_html_page(0)
        self.assertEqual("plain text<br />", new_text)

    def test_quotes_escaped(self):
        converter = HtmlPagesConverter(FakeFileWrapper("text with 'quotes'"))
        new_text = converter.get_html_page(0)
        self.assertEqual("text with &#x27;quotes&#x27;<br />", new_text)

    def test_random_access_pages(self):
        converter = HtmlPagesConverter(FakeFileWrapper("page one\nPAGE_BREAK\npage two\nPAGE_BREAK\npage three"))
        page_two = converter.get_html_page(1)
        self.assertEqual("page two<br />", page_two)


class FakeFileWrapper:
    def __init__(self, text):
        self.text = text

    def open(self):
        return io.StringIO(self.text)

我想分裂的想法是这样的


import html as html_converter


class FileAccessWrapper:
    def __init__(self, filename):
        self.filename = filename

    def open(self):
        return open(self.filename, "r", encoding="UTF-8")


class HtmlPagesConverter:

    def __init__(self, file_access):
        """Read the file and note the positions of the page breaks so we can access them quickly"""
        self.file_access = file_access
        self.breaks = [0]
        with self.file_access.open() as f:
            while True:
                line = f.readline()
                if not line:
                    break
                line = line.rstrip()
                if "PAGE_BREAK" in line:
                    page_break_position = f.tell()
                    self.breaks.append(f.tell())
            self.breaks.append(f.tell())                

    def get_html_page(self, page):
        """Return html page with the given number (zero indexed)"""
        page_start = self.breaks[page]
        page_end = self.breaks[page+1]
        html = ""
        with self.file_access.open() as f:
            f.seek(page_start)
            while f.tell() != page_end:
                line = f.readline()
                html = line
        return html

    def convert_html_page(self, page):
        """Convert html page with the given number"""
        page_start = self.breaks[page]
        page_end = self.breaks[page + 1]
        html = ""
        with self.file_access.open() as f:
            line = f.readline()
            line = line.rstrip()
            html += html_converter.escape(line, quote=True)
            html += "<br />"
        return html

然后将测试更改为在测试中以这种方式调用convert_html_page

import unittest
import os
import tempfile
import io

from html_pages import HtmlPagesConverter, FileAccessWrapper


class HtmlPagesTest(unittest.TestCase):
    def test_inserts_br_tags_for_linebreaks(self):
        filename = os.path.join(tempfile.gettempdir(), "afile.txt")
        f = open(filename, "w", encoding="UTF-8")
        f.write("plain text\n")
        f.close()
        converter = HtmlPagesConverter(FileAccessWrapper(filename))
        new_text = converter.convert_html_page(0)
        self.assertEqual("plain text<br />", new_text)

    def test_quotes_escaped(self):
        converter = HtmlPagesConverter(FakeFileWrapper("text with 'quotes'"))
        new_text = converter.convert_html_page(0)
        self.assertEqual("text with &#x27;quotes&#x27;<br />", new_text)

    def test_random_access_pages(self):
        converter = HtmlPagesConverter(FakeFileWrapper("page one\nPAGE_BREAK\npage two\nPAGE_BREAK\npage three"))
        page_two = converter.convert_html_page(1)
        self.assertEqual("page two<br />", page_two)


class FakeFileWrapper:
    def __init__(self, text):
        self.text = text

    def open(self):
        return io.StringIO(self.text)

但这会使测试失败并出现这些错误

Testing started at 21.05 ...
/home/af/Dokumenter/Programs/Python/venv/bin/python /usr/share/pycharm/helpers/pycharm/_jb_unittest_runner.py --path "/home/af/Dokumenter/Programs/Python/Example Files/Intermediate/fake/fake_example_after/test_html_pages.py"


Ran 3 tests in 0.002s

FAILED (failures=1)
Launching unittests with arguments python -m unittest /home/af/Dokumenter/Programs/Python/Example Files/Intermediate/fake/fake_example_after/test_html_pages.py in /home/af/Dokumenter/Programs/Python/Example Files/Intermediate/fake/fake_example_after


page one<br /> != page two<br />

Expected :page two<br />
Actual   :page one<br />
 <Click to see difference>

Traceback (most recent call last):
  File "/usr/share/pycharm/helpers/pycharm/teamcity/diff_tools.py", line 32, in _patched_equals
    old(self, first, second, msg)
  File "/usr/lib/python3.7/unittest/case.py", line 839, in assertEqual
    assertion_func(first, second, msg=msg)
  File "/usr/lib/python3.7/unittest/case.py", line 1220, in assertMultiLineEqual
    self.fail(self._formatMessage(msg, standardMsg))
  File "/usr/lib/python3.7/unittest/case.py", line 680, in fail
    raise self.failureException(msg)
AssertionError: 'page two<br />' != 'page one<br />'
- page two<br />
?      --
+ page one<br />
?       ++


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/unittest/case.py", line 59, in testPartExecutor
    yield
  File "/usr/lib/python3.7/unittest/case.py", line 615, in run
    testMethod()
  File "/home/af/Dokumenter/Programs/Python/Example Files/Intermediate/fake/fake_example_after/test_html_pages.py", line 27, in test_random_access_pages
    self.assertEqual("page two<br />", page_two)


Process finished with exit code 1

0 个答案:

没有答案