'Test the endpoint to fetch the health of a torrent'

@deferred(timeout=20)
@inlineCallbacks
def test_check_torrent_health(self):

    torrent_db = self.session.open_dbhandler(NTFY_TORRENTS)
    torrent_db.addExternalTorrentNoDef(('a' * 20), 'ubuntu-torrent.iso', [['file1.txt', 42]], (('udp://localhost:%s/announce' % self.udp_port), ('http://localhost:%s/announce' % self.http_port)), time.time())
    url = ('torrents/%s/health?timeout=10&refresh=1' % ('a' * 20).encode('hex'))
    self.should_check_equality = False
    (yield self.do_request(url, expected_code=400, request_type='GET'))
    def call_cb(infohash, callback, **_):
        callback({'seeders': 1, 'leechers': 2})
    self.session.lm.torrent_checker = TorrentChecker(self.session)
    self.session.lm.torrent_checker.initialize()
    self.session.lm.ltmgr = MockObject()
    self.session.lm.ltmgr.get_metainfo = call_cb
    (yield self.do_request(('torrents/%s/health' % ('f' * 40)), expected_code=404, request_type='GET'))
    def verify_response_no_trackers(response):
        json_response = json.loads(response)
        self.assertTrue(('DHT' in json_response['health']))
    def verify_response_with_trackers(response):
        json_response = json.loads(response)
        expected_dict = {u'health': {u'DHT': {u'leechers': 2, u'seeders': 1, u'infohash': (u'a' * 20).encode('hex')}, (u'udp://localhost:%s' % self.udp_port): {u'leechers': 20, u'seeders': 10, u'infohash': (u'a' * 20).encode('hex')}, (u'http://localhost:%s/announce' % self.http_port): {u'leechers': 30, u'seeders': 20, u'infohash': (u'a' * 20).encode('hex')}}}
        self.assertDictEqual(json_response, expected_dict)
    (yield self.do_request(url, expected_code=200, request_type='GET').addCallback(verify_response_no_trackers))
    self.udp_tracker.start()
    self.udp_tracker.tracker_info.add_info_about_infohash(('a' * 20), 10, 20)
    self.http_tracker.start()
    self.http_tracker.tracker_info.add_info_about_infohash(('a' * 20), 20, 30)
    (yield self.do_request(url, expected_code=200, request_type='GET').addCallback(verify_response_with_trackers))
