(url, *args, **kw)
| 837 | |
| 838 | |
| 839 | def open_urlresource(url, *args, **kw): |
| 840 | import urllib.request, urllib.parse |
| 841 | from .os_helper import unlink |
| 842 | try: |
| 843 | import gzip |
| 844 | except ImportError: |
| 845 | gzip = None |
| 846 | |
| 847 | check = kw.pop('check', None) |
| 848 | |
| 849 | filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! |
| 850 | |
| 851 | fn = os.path.join(TEST_DATA_DIR, filename) |
| 852 | |
| 853 | def check_valid_file(fn): |
| 854 | f = open(fn, *args, **kw) |
| 855 | if check is None: |
| 856 | return f |
| 857 | elif check(f): |
| 858 | f.seek(0) |
| 859 | return f |
| 860 | f.close() |
| 861 | |
| 862 | if os.path.exists(fn): |
| 863 | f = check_valid_file(fn) |
| 864 | if f is not None: |
| 865 | return f |
| 866 | unlink(fn) |
| 867 | |
| 868 | # Verify the requirement before downloading the file |
| 869 | requires('urlfetch') |
| 870 | |
| 871 | if verbose: |
| 872 | print('\tfetching %s ...' % url, file=get_original_stdout()) |
| 873 | opener = urllib.request.build_opener() |
| 874 | if gzip: |
| 875 | opener.addheaders.append(('Accept-Encoding', 'gzip')) |
| 876 | f = opener.open(url, timeout=INTERNET_TIMEOUT) |
| 877 | if gzip and f.headers.get('Content-Encoding') == 'gzip': |
| 878 | f = gzip.GzipFile(fileobj=f) |
| 879 | try: |
| 880 | with open(fn, "wb") as out: |
| 881 | s = f.read() |
| 882 | while s: |
| 883 | out.write(s) |
| 884 | s = f.read() |
| 885 | finally: |
| 886 | f.close() |
| 887 | |
| 888 | f = check_valid_file(fn) |
| 889 | if f is not None: |
| 890 | return f |
| 891 | raise TestFailed('invalid resource %r' % fn) |
| 892 | |
| 893 | |
| 894 | @contextlib.contextmanager |
searching dependent graphs…