为什么我的单元测试失败,当结果看起来"正确"对我来说?

时间:2018-02-28 17:32:27

标签: python

我正在尝试学习python。我从这个单元测试开始:

import unittest

from rna_transcription import to_rna

class RNATranscriptionTests(unittest.TestCase):

    def test_transcribes_cytosine_to_guanine(self):
        self.assertEqual(to_rna('C'), 'G')
if __name__ == '__main__':
    unittest.main()

我这样写了我的方法:

def to_rna(dna_strand):
    rna_strand = []

    for x in dna_strand:
        print('looking at:', x)
        if x == 'C':
            rna_strand.append('G')


    return rna_strand

当我运行单元测试时,它会因此错误而失败:

AssertionError: ['G'] != 'G'

我不确定这里有什么问题。我没有得到输出。除了用不同的书写方式,G对我来说看起来像G。我做错了什么?

1 个答案:

答案 0 :(得分:2)

['G']'G'不同。前者是list,后者是str。列表永远不能等于字符串。

但是你的测试是正确的,因为它指出你的函数的行为不是预期的行为。如果你想让它返回一个字符串,你需要它看起来像这样。

def to_rna(dna_strand):
    rna_strand = ''

    for x in dna_strand:
        print('looking at:', x)
        # if I recall my biology class correctly 
        rna_strand += 'G' if x == 'C' else x

    return rna_strand

请注意,有更有效的方法可以执行此操作,但为了示例,我没有过多地更新代码。你实际上可以这样做。

def to_rna(dna_strand):
    return dna_strand.replace('C', 'G')