如何在 Python Idle 中运行单元测试? [英] How to run Unit Test in Python Idle?

查看:36
本文介绍了如何在 Python Idle 中运行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的单词出现 Gui 项目创建了一个 python 单元测试,我想测试前 5 个单词的出现,因此它应该返回一个真值,但是我不知道如何运行单元测试?我正在尝试使用空闲 shell,但我应该使用 Visual Studio 命令提示符还是我的单元测试设置不正确的问题?如果您需要它来完成任务,我将显示下面的代码:

I created a python unit test for my word occurence Gui project, I want to test the occurrence of the top 5 words so it should return a true value however I can't figure out how to run the unit test? I'm trying to use idle shell but should I use the visual studio command prompt instead or is the problem with my unit test not being set up properly? I'll display the code below in case you need it for the task:

#Imports
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from collections import Counter
from tkinter import messagebox
import collections
import unittest 

# Initialize the dictionary
wordcount = {}

#Unit Test
class TestWordCount(unittest.TestCase):
    def test_count_words(self):
        n_print = 5
        expected_result = {
            'the' : 731,
            'and' : 565,
            'to' : 379,
            'of' : 342,
            'i' : 313
        }

        counter = n_print(int)
        result = counter.count_words()
        assert len(result) == len(expected_result)
        assert result == expected_result
        unittest.Word_Occurence_GUI().run(TestWordCount())
        

#open Macbeth text file
file = open('Macbeth Entire Play.txt', encoding="utf8")
a= file.read()

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__()  # Call __init__() method in parent (tk.Frame)
        
        self.label = tk.Button(self, text='How many words to Sort?', command=self.ask_count)
        self.label.grid(row=0)
        self.open_btn = tk.Button(text='Compute', command=self.ask_count)
        self.open_btn.pack(pady=(30,10))
        self.exit_btn = tk.Button(text='Exit', command=master.destroy)
        self.exit_btn.pack()

    def ask_count(self):
        
        with open('Macbeth Entire Play.txt', encoding="utf8") as file:
            self.file_text = file.read()
        for word in a.lower().split():
          word = word.replace(".","")
          word = word.replace(",","")
          word = word.replace(":","")
          word = word.replace("\"","")
          word = word.replace("!","")
          word = word.replace("“","")
          word = word.replace("‘","")
          word = word.replace("*","")
          if word not in wordcount:
              wordcount[word] = 1
          else:
              wordcount[word] += 1
        n_print = int(input("How many most common words are: "))
        print("\nThe {} most common words are as follows\n".format(n_print))
        word_counter = collections.Counter(wordcount)
        for word, count in word_counter.most_common(n_print):
          print(word, ": ", count)
        messagebox.showinfo("Top words...", "The top words are: \n" + "\n".join([(str(word)+": "+str(count)) for word, count in word_counter.most_common(n_print)]))

        # Close the file
        file.close()
        messagebox.showinfo("The top words are: ")

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Count words")
    root.geometry('400x400+900+50')
    app = Application(root)
    app.pack(expand=True, fill='both')
    root.mainloop()
    #run unit test
    unittest.main()

推荐答案

免责声明:不能回答您的问题.这只是一个示例,说明如何以编程方式使用 unittest 模块而不是从命令行并捕获其输出(尽管 不是来自 IDLE 和/或作为Tkinter 应用程序).但是,在您的 Tkinter 应用程序中,这两件事(用另一个它运行测试并捕获结果)都是必要的.)

Disclaimer: This does not answer your question. It's merely an example of how to use the unittest module programmatically as opposed to from the command-line and capture its output (although not from IDLE and/or as part of a Tkinter application). However both of these things (running the test from with another it and capturing the results) would be necessary lly in your Tkinter application.)

正在测试的代码做了一些与您在问题中所遇到的非常相似的事情.

The code being tested does several things very similar to what you have in your question.

也就是说,以两种不同的方式计算文本文件中的单词——实际上涉及两个单独的测试——一个使用 collections.Counter 字典子类,另一个使用相同的方法手动"完成.然后将每个结果与预期结果进行比较.

Which is, namely, to count the words in a text file two different ways — there's actually two separate tests involved — one uses a collections.Counter dictionary subclass and the other does to the same thing is done "manually". Afterwards the results of each are compared to the expected results.

以下是用于测试的非常测试文件的内容:

Here's the contents the very simple test file used for testing:

Here's one line
And another line
And another line make three

这是代码:

import collections
from io import StringIO
import unittest


class TestWordCounts(unittest.TestCase):
    TEST_FILENAME = './sample_e_input.txt'
    EXPECTED_RESULT = {"heres": 1,
                       'one': 1,
                       'line': 3,
                       'and': 2,
                       'another': 2,
                       'make': 1,
                       'three': 1}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.get_text()

    def test_collections_counter(self):
        ''' Count words collections.Counter. '''
        counter = collections.Counter((word for word in self.clean_text.split()))
        self.assertEqual(len(counter), len(self.EXPECTED_RESULT))
        self.assertEqual(counter, self.EXPECTED_RESULT)
        print('test_collections_counter passed')

    def test_manual_count(self):
        ''' Count words manually. '''
        word_counts = self.count_words(self.clean_text)
        self.assertEqual(len(word_counts), len(self.EXPECTED_RESULT))
        self.assertEqual(word_counts, self.EXPECTED_RESULT)
        print('test_manual_count passed')

    def get_text(self):
        ''' Read test file then convert to lowercase and remove punctuation. '''
        with open(self.TEST_FILENAME, encoding="utf8") as file:
            text = file.read()

        cleaned = text.lower()
        for substring in '. , : " \' ! *'.split():
            cleaned = cleaned.replace(substring, "")
        self.clean_text = cleaned

    def count_words(self, file_text):
        wordcount = collections.defaultdict(int)
        for word in file_text.split():
            wordcount[word] += 1
        return dict(wordcount)


if __name__ == '__main__':

    # Run unit test, capture output, and then print it.
    output = StringIO()
    tests = unittest.TestLoader().loadTestsFromTestCase(TestWordCounts)
    test_result = unittest.TextTestRunner(stream=output).run(tests)
    print(output.getvalue())  # Print captured output from running test.

输出打印:

test_collections_counter passed
test_manual_count passed
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

这篇关于如何在 Python Idle 中运行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆