Browse Source

Fix Unit-Test (and Proxy-Class when no Proxy was found)

bernhardbuhl 4 years ago
parent
commit
42d645eafc
3 changed files with 65 additions and 8 deletions
  1. 3 0
      baangt/base/ProxyRotate.py
  2. 43 7
      tests/test_PDFCompare.py
  3. 19 1
      tests/test_ProxyRotate.py

+ 3 - 0
baangt/base/ProxyRotate.py

@@ -290,6 +290,9 @@ class ProxyRotate(metaclass=Singleton):
             lCount += 1
             time.sleep(1)
         logger.critical(f"Proxies count: {len(self.proxies)}")
+        if len(self.proxies) == 0:
+            logger.critical("No proxy was found. Maybe internet down?")
+            raise BaseException("No proxy was found. Maybe internet down?")
         proxy = self.proxies[list(self.proxies.keys())[randint(0, len(self.proxies) - 1)]]
         proxy.Called()
         if proxy.username == "" and proxy.password == "":

+ 43 - 7
tests/test_PDFCompare.py

@@ -2,15 +2,42 @@ import pytest
 from os import getcwd
 from pathlib import Path
 from baangt.base.PDFCompare import PDFCompare, PDFCompareDetails
+import socket
 
+"""
 #####################
 ### Attention #######
 #####################
-# Before you run these tests, you'll have to run **flask run** in PDF-Comparison service on local host, or these
-# Tests will fail.
+# Before you run these tests, you'll have to run **flask run** in PDF-Comparison service on local host, or most of these
+# Tests will be skipped.
+
+# To do so (first start)
+git clone https://gogs.earthsquad.global/athos/baangt-PDFComparison
+cd baangt-PDFComparison
+virtualenv venv
+source venv/bin/activate
+pip install -r pdf_comaprison_flask_api/requirements.txt
+
+# Everytime:
+cd pdf_comaprison_flask_api
+export FLASK_APP=app.py 
+flask run 
+"""
 
 newOriginalFile1_UUID = None     # UUID of new example file 1
 
+def __checkSocketOpen() -> bool:
+    aSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    result = aSocket.connect_ex(("127.0.0.1", 5000))
+    aSocket.close()
+    if result == 0:
+        return True
+    else:
+        return False
+
+lPortOpen = __checkSocketOpen()
+
+
 def __getDictStructure():
     return {"referenceID": "",
             "BLOB": "",
@@ -22,7 +49,8 @@ def __getDictStructure():
 def __uploadNewFiles():
     global newOriginalFile2_UUID
     global newOriginalFile1_UUID
-    newOriginalFile1_UUID = __uploadNewFile(Path(getcwd()).joinpath("pdfs").joinpath("sample.pdf"))
+    newOriginalFile1_UUID = __uploadNewFile(Path(getcwd()).joinpath("tests").joinpath("pdfs").joinpath("sample.pdf"))
+
 
 def __uploadNewFile(fileNameAndPath):
     lFileDetails = PDFCompareDetails()
@@ -32,6 +60,8 @@ def __uploadNewFile(fileNameAndPath):
     assert lFileDetails.Status == "OK"
     return lFileDetails.newUUID
 
+
+@pytest.mark.skipif(lPortOpen==False, reason="PDF-Comparison service not available")
 def test_UploadNewFilesForTests():
     __uploadNewFiles()
     assert newOriginalFile1_UUID
@@ -55,9 +85,11 @@ def test_PDFCompare_withWrongFile():
 
     assert lDict["pdfThatdoesntExist.pdf"]["Status"] == 'NOK'
 
+
+@pytest.mark.skipif(lPortOpen==False, reason="PDF-Comparison service not available")
 def test_PDFCompare_withFileLoadOK():
     pdfCompare = PDFCompare()
-    lFile = Path(getcwd()).joinpath("pdfs").joinpath("sample.pdf")
+    lFile = Path(getcwd()).joinpath("tests").joinpath("pdfs").joinpath("sample.pdf")
 
     lDict = {lFile: __getDictStructure()}
     lDict[lFile]["referenceID"] = newOriginalFile1_UUID
@@ -67,9 +99,11 @@ def test_PDFCompare_withFileLoadOK():
     assert len(lDict[lFile]["newUUID"]) > 0
     assert lDict[lFile]["Status"] == "OK"
 
+
+@pytest.mark.skipif(lPortOpen==False, reason="PDF-Comparison service not available")
 def test_PDFCompare_withFileLoadNOK():
     pdfCompare = PDFCompare()
-    lFile = Path(getcwd()).joinpath("pdfs").joinpath("sample2.pdf")
+    lFile = Path(getcwd()).joinpath("tests").joinpath("pdfs").joinpath("sample2.pdf")
 
     lDict = {lFile: __getDictStructure()}
     lDict[lFile]["referenceID"] = newOriginalFile1_UUID
@@ -79,10 +113,11 @@ def test_PDFCompare_withFileLoadNOK():
     assert len(lDict[lFile]["newUUID"]) > 0
     assert lDict[lFile]["Status"] == "NOK"
 
+
 def test_PDFCompare_withDataClass():
     pdfCompare = PDFCompare()
     pdfDataClass = PDFCompareDetails()
-    pdfDataClass.fileName = Path(getcwd()).joinpath("pdfs").joinpath("sample.pdf")
+    pdfDataClass.fileName = Path(getcwd()).joinpath("tests").joinpath("pdfs").joinpath("sample.pdf")
     pdfDataClass.referenceID = "12345"
 
     lDict = {pdfDataClass.fileName: pdfDataClass}
@@ -92,9 +127,10 @@ def test_PDFCompare_withDataClass():
     assert lDict[pdfDataClass.fileName].Status == "NOK"
     assert "Config wrong?" in lDict[pdfDataClass.fileName].StatusText
 
+
 def test_PDFCompare_withWrongURL():
     pdfCompare = PDFCompare(baseURL="http://franzi.fritzi:4711")
-    lFile = Path(getcwd()).joinpath("pdfs").joinpath("sample.pdf")
+    lFile = Path(getcwd()).joinpath("tests").joinpath("pdfs").joinpath("sample.pdf")
 
     lDict = {lFile: __getDictStructure()}
 

+ 19 - 1
tests/test_ProxyRotate.py

@@ -255,7 +255,7 @@ def test_recheckProxies_proxy_list_failed_html_body(mock_csv_DictReader, mock_ti
 
 @patch('time.sleep', return_value = None) 
 @patch("csv.DictReader")
-@pytest.mark.parametrize("proxyInitLength", [10, 700, 0])
+@pytest.mark.parametrize("proxyInitLength", [10, 700])
 def test_random_proxy(mock_csv_DictReader, mock_time_sleep, proxyInitLength):
     """ 
     Test random proxy return function
@@ -273,6 +273,24 @@ def test_random_proxy(mock_csv_DictReader, mock_time_sleep, proxyInitLength):
     assert isinstance(result["type"], str)
     assert proxyRotate.proxies[result["ip"]].called == 1
 
+
+@patch('time.sleep', return_value = None)
+@patch("csv.DictReader")
+@pytest.mark.parametrize("proxyInitLength", [0])
+def test_random_proxy_no_proxy_found(mock_csv_DictReader, mock_time_sleep, proxyInitLength):
+    """
+    Test random proxy return function
+
+    When called with "value=0" it will not be able to provide a Proxy-Server as no Proxy servers can be found.
+    """
+    # Initialize proxy list
+    proxyRotate = init_ProxyRotate(mock_csv_DictReader, proxyInitLength)
+    proxyRotate.proxies = proxyRotate.all_proxies
+
+    with pytest.raises(BaseException):
+        result = proxyRotate.random_proxy()
+
+
 @patch("csv.DictReader")
 @pytest.mark.parametrize("failedCounter", list(range(0,GC.PROXY_FAILCOUNTER)))
 @pytest.mark.parametrize("proxyInitLength", [10])