NameError:未定义名称“zombie_array”

时间:2018-04-26 01:52:03

标签: python python-2.7 unit-testing testing

我有一个python代码(q4.py),如下所示:

#!/usr/bin/env python


def DFS(j, visited, zombies, row):
    for k in range(row):
        if zombies[j][k] == '1' and visited[j][k] == False and visited[k][j] == False:
            visited[j][k] = True
            visited[k][j] = True
            DFS(k, visited, zombies, row)


def zombieCluster(zombies):
    row = len(zombies)
    col = len(zombies[0])
    count = 0
    if row == 0 or col == 0:
        return count
    visited = [[False for j in range(col)] for i in range(row)]
    for i in range(row):
        bol = False
        for j in range(row):
            if zombies[i][j] == '1' and visited[i][j] == False and visited[j][i] == False:
                visited[i][j] = True
                visited[j][i] = True
                DFS(j, visited, zombies, row)
                if bol == 0:
                    count += 1
                    bol = True
    return count


if __name__ == '__main__':
    # array input of zombie
    zombie_array = list()
    zombie_count = int(input())
    for i in range(int(zombie_count)):
        n = raw_input()
        zombie_array.append(str(n))

# zombie_array = ["1100" ,"1110", "0110", "0001"]
# print out the result
print(zombieCluster(zombie_array))

我正在为下面给出的代码编写测试代码(test_q4.py):

# -*- coding: utf-8 -*-
import unittest
import os
import sys

BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
sys.path.insert(0, BASEDIR)

from q4 import zombieCluster


class Test(unittest.TestCase):
    def testzombieCluster(self):
        zombie_array = ["1100", "1110", "0110", "0001"]
        expect = 2
        result = zombieCluster(zombie_array)
        self.assertEqual(result, expect)


if __name__ == '__main__':
     unittest.main()

但是当我从控制台运行此命令python test_q4.py时,它会发出错误:

Traceback (most recent call last):
  File "test_q4.py", line 9, in <module>
    from q4 import zombieCluster
  File "/home/rowle/Desktop/python/solution/q4.py", line 42, in <module>
    print(zombieCluster(zombie_array))
NameError: name 'zombie_array' is not defined

当我从源代码中删除print(zombieCluster(zombie_array))时,我的测试运行良好,但如果删除此行,我将看不到任何输出。

在这种情况下,我应该怎么做测试代码? 此外,如何测试源代码的主要功能?

1 个答案:

答案 0 :(得分:0)

创建一个def main()并按下代码放下代码:

#mc_embed_signup {
    background: rgba(0, 0, 0, 0) !important;
    color: #ffffff;
    padding: 0px;
    text-align: center;
}