|
1 | 1 | import os |
2 | | -from packaging.version import Version |
| 2 | +import socket |
| 3 | +from urllib.request import URLError, urlopen |
3 | 4 |
|
4 | | -import pytest |
5 | 5 | import matplotlib.ft2font |
6 | | -from urllib.request import urlopen, URLError |
| 6 | +import pytest |
| 7 | +from packaging.version import Version |
7 | 8 |
|
8 | 9 | from oggm import cfg |
9 | 10 | from oggm.utils import SAMPLE_DATA_COMMIT |
|
12 | 13 |
|
13 | 14 | # Matplotlib version changes plots, too |
14 | 15 | HAS_MPL_FOR_TESTS = False |
15 | | -if Version(matplotlib.__version__) >= Version('2'): |
| 16 | +if Version(matplotlib.__version__) >= Version("2"): |
16 | 17 | HAS_MPL_FOR_TESTS = True |
17 | 18 | BASELINE_DIR = os.path.join(cfg.CACHE_DIR, |
18 | 19 | 'oggm-sample-data-%s' % SAMPLE_DATA_COMMIT, |
19 | 20 | 'baseline_images', 'freetype_28') |
20 | 21 |
|
21 | | -# quick n dirty method to see if internet is on |
22 | | -try: |
23 | | - _ = urlopen('http://www.google.com', timeout=1) |
24 | | - HAS_INTERNET = True |
25 | | -except URLError: |
26 | | - HAS_INTERNET = False |
| 22 | +def check_internet_access( |
| 23 | + hostname: str = "8.8.8.8", port: int = 53, timeout: int = 1 |
| 24 | +): |
| 25 | + """Check if Internet is available. |
| 26 | + |
| 27 | + hostname : str, default "8.8.8.8" |
| 28 | + Web address. Can be a public DNS or an HTTP link. |
| 29 | + port : int, default 53 |
| 30 | + An open and unfiltered port number. This should be 53 for |
| 31 | + the domain, or 443 for https. |
| 32 | + timeout : int, default 1 |
| 33 | + Time in seconds before the connection times out. |
| 34 | +
|
| 35 | + """ |
| 36 | + try: |
| 37 | + socket.setdefaulttimeout(timeout) |
| 38 | + socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((hostname, port)) |
| 39 | + return True |
| 40 | + except socket.error as e: |
| 41 | + return False |
| 42 | + |
| 43 | +HAS_INTERNET = check_internet_access() |
27 | 44 |
|
28 | 45 |
|
29 | 46 | def mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance=1, **kwargs): |
|
0 commit comments