Skip to main content
 首页 » 编程设计

python之基于类似于 RSpec 的嵌套上下文组织 Python unittest 测试

2025年05月04日12JustinYoung

在编写 RSpec 测试时,我发现它使用的嵌套上下文结构非常清晰和有用:

describe "a laptop" do 
  before(:each) do 
  end 
  context "progamming" do 
    before(:each) do 
    end 
    it "compiles programs" do 
    end 
    context "with an external monitor" do 
      it "shows editors in multiple displays" do 
      end 
    end 
  end 
  context "video gaming" do 
    before(:each) do 
    end 
    context "with normal graphic card" do 
      before(:each) do 
      end 
      it "can not play League of Legends" do 
      end 
    end 
    context "with expensive graphic card" do 
      before(:each) do 
      end 
      it "can play League of Legends" do 
      end 
    end 
  end 
end 

在嵌套时共享/DRY 那些设置和拆卸代码非常容易,并且使用上下文结构也有助于“思考”规范的覆盖范围。我想知道我们通常如何编写 Python 单元测试来实现这一点。还是理念不同?

看起来我们可以通过 inheriting the test class 实现类似的设置/拆卸代码共享, 但仍然存在一些小问题,将它们分离在不同的类中似乎不是一个非常可读/可维护的结构,如果它去,比如更深 2 层。

请您参考如下方法:

一定要看看 python 中的一些 BDD 框架。

  1. 表现 - http://pythonhosted.org/behave/
  2. 生菜 - http://lettuce.it/intro/overview.html

主要模仿 Cucumber,Ruby 中的 bdd 框架,它是 RSpec 中第一个基于故事的框架。

不确定这是否完全回答了您的问题,但我希望您会发现它有用。

同时查看 Dan North 的博客。关于一般发展的哲学和原则的真正好东西。 http://dannorth.net/

此外,我认为您会发现另一个有用的方面是使用由外向内和由内向外方法的 tdd 概念。 Rspec/BDD,我认为遵循由外而内的模型。你可以好好看看这个讨论,我觉得它非常有用 https://softwareengineering.stackexchange.com/questions/166409/tdd-outside-in-vs-inside-out