Python / Django : 단위 테스트 결과에 특정 문자열이 포함되어 있다고 주장하는 방법은 무엇입니까?
파이썬 단위 테스트 (실제로 Django)에서 assert내 테스트 결과에 내가 선택한 문자열이 포함되어 있는지 알려주 는 올바른 문장 은 무엇 입니까?
self.assertContainsTheString(result, {"car" : ["toyota","honda"]})
result위의 두 번째 인수로 지정한 json 객체 (또는 문자열)가 최소한 포함되어 있는지 확인하고 싶습니다.
{"car" : ["toyota","honda"]}
self.assertContains(result, "abcd")
json과 함께 작동하도록 수정할 수 있습니다.
개체 self.assertContains에만 사용하십시오 HttpResponse. 다른 개체의 경우 self.assertIn.
문자열이 다른 문자열의 하위 문자열인지 아닌지 확인하려면 assertIn및 assertNotIn다음 을 사용해야합니다 .
# Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
Python 2.7 및 Python 3.1 이후 새로운 기능입니다.
간단한 assertTrue + in python 키워드를 사용하여 다른 문자열에서 예상되는 문자열 부분에 대한 단언을 작성할 수 있습니다.
self.assertTrue("expected_part_of_string" in my_longer_string)
.NET을 사용하여 JSON 개체를 빌드합니다 json.dumps().
그런 다음 assertEqual(result, your_json_dict)
import json
expected_dict = {"car":["toyota", "honda"]}
expected_dict_json = json.dumps(expected_dict)
self.assertEqual(result, expected_dict_json)
Ed I가 언급했듯이 , assertIn아마도 하나의 문자열을 다른 문자열에서 찾는 가장 간단한 대답 일 것입니다. 그러나 질문은 다음과 같습니다.
result위의 두 번째 인수로 지정한 json 객체 (또는 문자열)가 최소한 포함되어 있는지 확인하고 싶습니다 .{"car" : ["toyota","honda"]}
따라서 실패시 유용한 메시지가 수신되도록 여러 단언을 사용합니다. 테스트는 원래 작성하지 않은 사람이 향후 테스트를 이해하고 유지해야합니다. 따라서 우리가 내부에 있다고 가정합니다 django.test.TestCase.
# Check that `car` is a key in `result`
self.assertIn('car', result)
# Compare the `car` to what's expected (assuming that order matters)
self.assertEqual(result['car'], ['toyota', 'honda'])
다음과 같은 유용한 메시지를 제공합니다.
# If 'car' isn't in the result:
AssertionError: 'car' not found in {'context': ..., 'etc':... }
# If 'car' entry doesn't match:
AssertionError: Lists differ: ['toyota', 'honda'] != ['honda', 'volvo']
First differing element 0:
toyota
honda
- ['toyota', 'honda']
+ ['honda', 'volvo']
나는 비슷한 문제에 처해 있고 render_content 속성을 사용 했기 때문에
assertTrue('string' in response.rendered_content) 유사하게
assertFalse('string' in response.rendered_content) if I want to test that a string is not rendered
But it also worked the early suggested method,
AssertContains(response, 'html string as rendered')
So I'd say that the first one is more straightforward. I hope it will help.
ReferenceURL : https://stackoverflow.com/questions/17536916/python-django-how-to-assert-that-unit-test-result-contains-a-certain-string
'Program Club' 카테고리의 다른 글
| CSS 텍스트 랩 없음 (0) | 2021.01.09 |
|---|---|
| Vim 일반 모드에서 빠르게 버퍼 전환 (0) | 2021.01.09 |
| Rails에서 문자열을 URL 이스케이프하려면 어떻게해야합니까? (0) | 2021.01.09 |
| Gradle-Java 플러그인의 jar 파일 이름 (0) | 2021.01.09 |
| 작업을 취소하면 예외가 발생합니다. (0) | 2021.01.09 |