Skip to content

测试 UserNodeService #9

@codetalks-new

Description

@codetalks-new

测试准备

  1. 准备一些 node 的 fixtures ,示例如下:
@pytest.fixture()
def node_py():
    return Node.objects.filter(code="python").first()


@pytest.fixture()
def node_flask():
    return Node.objects.filter(code="flask").first()

一开始写上面的代码时,后面有几个 fixture 中的查询忘记调用 first() 了。导致后面在 filter 查询 中使用 node 时引发了下面的错误信息:

The QuerySet value for an exact lookup must be limited to one result using slicing.

意思是 filter 中的相等查询(exact lookup) 不能使用 QuerySet 作为参数。

同时也为 UserNodeService 添加几个接口。

  def _check_star_state(self, node: Node, state: UserNodeStarState):
    return UserNodeStar.objects.filter(user=self.user, node=node, state=state).exists()
  
  def has_star(self, node: Node):
    """是否已关注"""
    return self._check_star_state(node, UserNodeStarState.FOLLOWING)

  def has_block(self, node: Node):
    """是否已屏蔽"""
    return self._check_star_state(node, UserNodeStarState.BLOCKING)

单元测试

下面是测试用例,为了一失一般性,通过 fixtures 引入了多个 node

def test_toggle_star_node(ut1, node_c, node_py, node_js):
  service1 = UserNodeService(ut1)
  nodes = [node_c, node_js, node_py]
  for node in nodes:
    assert not service1.has_star(node)
    assert not service1.has_block(node)

  for node in nodes:
    service1.star_node(node)
    assert service1.has_star(node)
    assert not service1.has_block(node)
    service1.unstar_node(node)
    assert not service1.has_star(node)
    assert not service1.has_block(node)

  for node in nodes:
    service1.block_node(node)
    assert service1.has_block(node)
    assert not service1.has_star(node)
    service1.unblock_node(node)
    assert not service1.has_star(node)
    assert not service1.has_block(node)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions