#!/usr/bin/python
"""
$Id: external_resources.py,v 1.9 2006/11/14 18:11:38 dom Exp $

The ExternalResourcesTestCase implements the validator.testcase.TestCase
interface for the tests related to the following BP:
Keep the number of externally linked resources to a minimum.


License
-------
Copyright (c) 2006 World Wide Web Consortium, (Massachusetts
Institute of Technology, European Research Consortium for Informatics
and Mathematics, Keio University). All Rights Reserved. This work is
distributed under the W3C Software License [1] in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

[1] http://www.w3.org/Consortium/Legal/copyright-software

"""



from  validator import testcase,utils

# Tests regarding the EXTERNAL_RESOURCES and BALANCE BP
class ExternalResourcesTestCase(testcase.LinksBasedTestCase):
    BpId=["EXTERNAL_RESOURCES","BALANCE"]

    def _observeLinks(self):
        import validator.utils
        links = self.getLinks()
        uris = []
        countExternalResources = 0
        countLinks = 0
        for link in links:
            if link.nature==utils.LINK_TYPE_EMBED and not link.target in uris:
                # @@@ Should only count once when there are imbricated objects
                countExternalResources = countExternalResources + 1
                uris.append(link.target)
            elif link.nature==utils.LINK_TYPE_EXT:
                countLinks = countLinks + 1
        if countExternalResources:
            if countExternalResources > 20:
                self.addObservation(Observation("ER3",testcase.Location(self.uri),{"count":countExternalResources}))
            elif countExternalResources > 10:
                self.addObservation(Observation("ER2",testcase.Location(self.uri),{"count":countExternalResources}))
            else:
                self.addObservation(Observation("ER1",testcase.Location(self.uri),{"count":countExternalResources}))
        if countLinks:
            self.addObservation(Observation("BA1",testcase.Location(self.uri),{"count":countLinks}))
                
# -------------------------
# Unit tests for this module
import unittest

from validator.testcase import TestResults, Observation, Location, LineColumnLocation
class Tests(unittest.TestCase):
    def _test(self,inp,res):
        a = ExternalResourcesTestCase()
        self.assertEqual(a.run(inp),res)
    
    def testWithExtRes(self):
        inp = "http://dev.w3.org/cvsweb/~checkout~/2006/mwbp-validator/tests/external-resources-1.xhtml"
        res = TestResults(
            [Observation("ER1",Location(inp),{"count":5}),
             Observation('BA1',Location(inp),{'count': 1})
             ]
            )
        self._test(inp,res)


def _test():
    unittest.main()

if __name__ == '__main__':
    _test()



