diff --git a/pybatfish/client/internal.py b/pybatfish/client/internal.py index f983f303..3aca97c7 100644 --- a/pybatfish/client/internal.py +++ b/pybatfish/client/internal.py @@ -16,11 +16,10 @@ from typing import TYPE_CHECKING, Any, Dict, Optional, Union from pybatfish.client import restv2helper -from pybatfish.client.consts import CoordConsts from pybatfish.datamodel.answer import Answer from pybatfish.util import get_uuid -from . import resthelper, workhelper +from . import workhelper from .options import Options if TYPE_CHECKING: @@ -40,17 +39,7 @@ def _bf_answer_obj( question_name = Options.default_question_prefix + "_" + get_uuid() # Upload the question - if session.use_deprecated_workmgr_v1(): - json_data = workhelper.get_data_upload_question( - session, - question_name, - question_str, - ) - resthelper.get_json_response( - session, CoordConsts.SVC_RSC_UPLOAD_QUESTION, json_data - ) - else: - restv2helper.upload_question(session, question_name, question_str) + restv2helper.upload_question(session, question_name, question_str) # Answer the question work_item = workhelper.get_workitem_answer( diff --git a/pybatfish/client/resthelper.py b/pybatfish/client/resthelper.py deleted file mode 100644 index 0a64bd4d..00000000 --- a/pybatfish/client/resthelper.py +++ /dev/null @@ -1,116 +0,0 @@ -# Copyright 2018 The Batfish Open Source Project -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import TYPE_CHECKING, Any, Dict, Optional # noqa: F401 - -import requests -from requests import Response # noqa: F401 -from requests.adapters import HTTPAdapter -from requests_toolbelt.multipart.encoder import MultipartEncoder -from urllib3 import Retry - -import pybatfish -from pybatfish.client.consts import CoordConsts -from pybatfish.exception import BatfishException - -from .options import Options - -if TYPE_CHECKING: - from pybatfish.client.session import Session # noqa: F401 - -# Create session for existing connection to backend -_requests_session = requests.Session() -_adapter = HTTPAdapter( - max_retries=Retry( - total=Options.max_retries_to_connect_to_coordinator, - connect=Options.max_retries_to_connect_to_coordinator, - read=Options.max_retries_to_connect_to_coordinator, - backoff_factor=Options.request_backoff_factor, - # Retry on all calls, including POST - allowed_methods=None, - status_forcelist=[429, 500, 502, 503, 504], - ) -) -# Configure retries for http and https requests -_requests_session.mount("http://", _adapter) -_requests_session.mount("https://", _adapter) - - -# uncomment line below if you want http capture by fiddler -# _requests_session.proxies = {'http': 'http://127.0.0.1:8888', -# 'https': 'http://127.0.0.1:8888'} - - -def get_json_response(session, resource, jsonData=None, useHttpGet=False): - # type: (Session, str, Optional[Dict], bool) -> Dict[str, Any] - """Send a request (POST or GET) to Batfish. - - :param session: :py:class:`~pybatfish.client.session.Session` object to use - :param resource: the API endpoint to call on the Batfish server, string - :param jsonData: any HTTP POST data to send, as a dictionary - :param useHttpGet: boolean, whether HTTP GET request should be sent - """ - assert session.use_deprecated_workmgr_v1() - if useHttpGet: - response = _get_data(session, resource) - else: - response = _post_data(session, resource, jsonData) - - json_response = response.json() - if json_response[0] != CoordConsts.SVC_KEY_SUCCESS: - raise BatfishException(f"Coordinator returned failure: {json_response[1]}") - - return dict(json_response[1]) - - -def _post_data(session, resource, json_data, stream=False): - # type: (Session, str, Optional[Dict], bool) -> Response - """Send a POST request.""" - return _make_request(session, resource, json_data, stream, False) - - -def _get_data(session, resource, stream=False): - # type: (Session, str, bool) -> Response - """Send a GET request.""" - return _make_request(session, resource, stream=stream, use_http_get=True) - - -def _make_request(session, resource, json_data=None, stream=False, use_http_get=False): - # type: (Session, str, Optional[Dict], bool, bool) -> Response - """Actually make a HTTP(s) request to Batfish coordinator. - - :raises SSLError if SSL connection failed - :raises ConnectionError if the coordinator is not available - """ - url = session.get_url(resource) - if use_http_get: - response = _requests_session.get( - url, verify=session.verify_ssl_certs, stream=stream - ) - else: - if json_data is None: - json_data = {} - json_data[CoordConsts.SVC_KEY_VERSION] = pybatfish.__version__ - multipart_data = MultipartEncoder(json_data) - headers = {"Content-Type": multipart_data.content_type} - response = _requests_session.post( - url, - data=multipart_data, - verify=session.verify_ssl_certs, - stream=stream, - headers=headers, - ) - response.raise_for_status() - return response diff --git a/pybatfish/client/session.py b/pybatfish/client/session.py index 9b40be2b..2f16d375 100644 --- a/pybatfish/client/session.py +++ b/pybatfish/client/session.py @@ -37,7 +37,7 @@ from deprecated import deprecated from requests import HTTPError -from pybatfish.client import resthelper, restv2helper, workhelper +from pybatfish.client import restv2helper, workhelper from pybatfish.client._facts import get_facts, load_facts, validate_facts, write_facts from pybatfish.client.asserts import ( assert_filter_denies, @@ -344,8 +344,6 @@ class Session: :ivar port_v2: The additional port of batfish service (9996 by default) :ivar ssl: Whether to use SSL when connecting to Batfish (False by default) :ivar api_key: Your API key - :ivar use_deprecated_workmgr_v1: Whether to use WorkMgrV1 instead of V2 for calls added in API - version 2.1.0. See help(Session.use_deprecated_workmgr_v1). """ def __init__( @@ -357,12 +355,9 @@ def __init__( verify_ssl_certs: bool = Options.verify_ssl_certs, api_key: str = CoordConsts.DEFAULT_API_KEY, load_questions: bool = True, - use_deprecated_workmgr_v1: bool | None = None, ): # Coordinator args self.host: str = host - self.port_v1: int = port_v1 - self._base_uri_v1: str = CoordConsts.SVC_CFG_WORK_MGR self.port_v2: int = port_v2 self._base_uri_v2: str = CoordConsts.SVC_CFG_WORK_MGR2 self.ssl: bool = ssl @@ -387,13 +382,6 @@ def __init__( if load_questions: self.q.load() - self._use_deprecated_workmgr_v1: bool | None = use_deprecated_workmgr_v1 - if self._use_deprecated_workmgr_v1 is None: - use_v1_env = os.environ.get(_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV) - if use_v1_env: - self._use_deprecated_workmgr_v1 = bool(int(use_v1_env)) - # if still None, will be set upon first query - # Support old property names @property @deprecated(reason="Use the new additional_args field instead") @@ -435,16 +423,6 @@ def coordinatorHost(self): def coordinatorHost(self, val): self.host = val - @property - @deprecated(reason="Use the new port_v1 field instead") - def coordinatorPort(self): - return self.port_v1 - - @coordinatorPort.setter - @deprecated(reason="Use the new port_v1 field instead") - def coordinatorPort(self, val): - self.port_v1 = val - @property @deprecated(reason="Use the new port_v2 field instead") def coordinatorPort2(self): @@ -742,13 +720,6 @@ def get_answer( else: return Answer(ans) - def get_base_url(self) -> str: - """Generate the base URL for connecting to Batfish coordinator.""" - protocol = "https" if self.ssl else "http" - return "{}://{}:{}{}".format( - protocol, self.host, self.port_v1, self._base_uri_v1 - ) - def get_base_url2(self) -> str: """Generate the base URL for V2 of the coordinator APIs.""" protocol = "https" if self.ssl else "http" @@ -869,15 +840,6 @@ def get_snapshot_object_text( ret: str = stream.read().decode(encoding) return ret - def get_url(self, resource: str) -> str: - """ - Get URL for the specified resource. - - :param resource: URI of the requested resource - :type resource: str - """ - return f"{self.get_base_url()}/{resource}" - def get_work_status(self, work_item): """Get the status for the specified work item.""" self._check_network() @@ -978,13 +940,7 @@ def init_snapshot_from_text( return ss_name def __init_snapshot_from_io(self, name: str, fd: IO) -> None: - if self.use_deprecated_workmgr_v1(): - json_data = workhelper.get_data_upload_snapshot(self, name, fd) - resthelper.get_json_response( - self, CoordConsts.SVC_RSC_UPLOAD_SNAPSHOT, json_data - ) - else: - restv2helper.upload_snapshot(self, name, fd) + restv2helper.upload_snapshot(self, name, fd) def __init_snapshot_from_file(self, name: str, file_to_send: str) -> None: tmp_file_name: str | None = None @@ -1075,13 +1031,6 @@ def list_incomplete_works(self) -> dict[str, Any]: :rtype: dict """ self._check_network() - - if self.use_deprecated_workmgr_v1(): - json_data = workhelper.get_data_list_incomplete_work(self) - response = resthelper.get_json_response( - self, CoordConsts.SVC_RSC_LIST_INCOMPLETE_WORK, json_data - ) - return response statuses = restv2helper.list_incomplete_work(self) return {CoordConsts.SVC_KEY_WORK_LIST: json.dumps(statuses)} @@ -1167,24 +1116,8 @@ def set_network( if e.response is None or e.response.status_code != 404: raise BatfishException("Unknown error accessing network", e) - if self.use_deprecated_workmgr_v1(): - json_data = workhelper.get_data_init_network(self, name) - json_response = resthelper.get_json_response( - self, CoordConsts.SVC_RSC_INIT_NETWORK, json_data - ) - - network_name = json_response.get(CoordConsts.SVC_KEY_NETWORK_NAME) - if network_name is None: - raise BatfishException( - "Network initialization failed. Server response: {}".format( - json_response - ) - ) - else: - restv2helper.init_network(self, name) - network_name = name - - self.network = str(network_name) + restv2helper.init_network(self, name) + self.network = str(name) return self.network def set_snapshot(self, name: str | None = None, index: int | None = None) -> str: @@ -1331,21 +1264,6 @@ def auto_complete( if max_suggestions and max_suggestions < 0: raise ValueError("max_suggestions cannot be negative") self._check_network() - if self.use_deprecated_workmgr_v1(): - json_data = workhelper.get_data_auto_complete( - self, completion_type, query, max_suggestions - ) - response = resthelper.get_json_response( - self, CoordConsts.SVC_RSC_AUTO_COMPLETE, json_data - ) - if CoordConsts.SVC_KEY_SUGGESTIONS in response: - suggestions = [ - AutoCompleteSuggestion.from_dict(json.loads(suggestion)) - for suggestion in response[CoordConsts.SVC_KEY_SUGGESTIONS] - ] - return suggestions - - raise BatfishException(f"Unexpected response: {response}.") response = restv2helper.auto_complete( self, completion_type, query, max_suggestions ) @@ -1360,33 +1278,6 @@ def auto_complete( ) return results - def use_deprecated_workmgr_v1(self) -> bool: - """Whether to use WorkMgrV1 instead of v2 for API calls added in API version 2.1.0 - - WorkMgrV1 is deprecated, and will be removed from backend Batfish in the near future. - - The decision to use old WorkMgrV1 calls instead of their ported versions in API version - 2.1.0 is made as follows: - - If use_deprecated_workmgr_v1=True is passed to Session(): use V1 - Else if use_deprecated_workmgr_v1=False is passed to Session(): use V2 - Else: - If pybf_use_deprecated_workmgr_v1=1 is set in the environment: use V1 - Else if pybf_use_deprecated_workmgr_v1=0 is set in the environment: use V2 - Else: - If result of backend version query for API version is >= 2.1.0: use V2 - Else (no api version returned or api version < 2.1.0): use V1 - """ - if self._use_deprecated_workmgr_v1 is None: - self._use_deprecated_workmgr_v1 = not self._backend_supports_exclusive_v2() - return self._use_deprecated_workmgr_v1 - - def _backend_supports_exclusive_v2(self) -> bool: - v2_api_version = restv2helper.get_api_version(self) - return not _version_less_than( - _version_to_tuple(str(v2_api_version)), _version_to_tuple("2.1.0") - ) - def _text_with_platform(text: str, platform: str | None) -> str: """Returns the text with platform prepended if needed.""" @@ -1425,6 +1316,3 @@ def _version_less_than(version: tuple[int, ...], min_version: tuple[int, ...]) - return version < min_version # Dev version is considered newer than any version return False - - -_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV = "pybf_use_deprecated_workmgr_v1" diff --git a/pybatfish/client/workhelper.py b/pybatfish/client/workhelper.py index f75af28a..1927195e 100644 --- a/pybatfish/client/workhelper.py +++ b/pybatfish/client/workhelper.py @@ -29,7 +29,7 @@ from pybatfish.client.consts import BfConsts, CoordConsts, CoordConstsV2, WorkStatusCode from pybatfish.exception import BatfishException -from . import resthelper, restv2helper +from . import restv2helper from .workitem import WorkItem # noqa: F401 # Maximum log length to display on execution errors, so we don't overload user with a huge log string @@ -149,16 +149,6 @@ def execute(work_item, session, background=False, extra_args=None): def queue_work(session: "Session", work_item: WorkItem) -> Dict[str, Any]: - if session.use_deprecated_workmgr_v1(): - json_data = { - CoordConsts.SVC_KEY_WORKITEM: work_item.to_json(), - CoordConsts.SVC_KEY_API_KEY: session.api_key, - } - # Submit the work item - response = resthelper.get_json_response( - session, CoordConsts.SVC_RSC_QUEUE_WORK, json_data - ) - return response restv2helper.queue_work(session, work_item) return {"result": True} @@ -338,22 +328,6 @@ def get_workitem_parse(session, snapshot): def get_work_status(w_item_id: str, session: "Session") -> Dict[str, Any]: - if session.use_deprecated_workmgr_v1(): - json_data = { - CoordConsts.SVC_KEY_API_KEY: session.api_key, - CoordConsts.SVC_KEY_WORKID: w_item_id, - } - answer = resthelper.get_json_response( - session, CoordConsts.SVC_RSC_GET_WORKSTATUS, json_data - ) - - if CoordConsts.SVC_KEY_WORKSTATUS in answer: - return answer - else: - raise BatfishException( - "Expected key (%s) not found in status check response: %s" - % (CoordConsts.SVC_KEY_WORKSTATUS, answer) - ) answer = restv2helper.get_work_status(session, w_item_id) return { CoordConsts.SVC_KEY_WORKSTATUS: answer.get(CoordConstsV2.PROP_WORK_STATUS_CODE), diff --git a/tests/client/test_assert.py b/tests/client/test_assert.py index 4b62a550..292ecd0a 100644 --- a/tests/client/test_assert.py +++ b/tests/client/test_assert.py @@ -98,7 +98,7 @@ def answer(self, *args, **kwargs): def test_filter_denies(): """Confirm filter-denies assert passes and fails as expected when specifying a session.""" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "searchFilters", create=True) as mock_search_filters: # Test success mock_search_filters.return_value = MockQuestion() @@ -126,7 +126,7 @@ def test_filter_denies(): def test_filter_denies_from_session(): """Confirm filter-denies assert passes and fails as expected when called from a session.""" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "searchFilters", create=True) as mock_search_filters: # Test success mock_search_filters.return_value = MockQuestion() @@ -154,7 +154,7 @@ def test_filter_denies_from_session(): def test_filter_has_no_unreachable_lines(): """Confirm filter-has-no-unreachable-lines assert passes and fails as expected when specifying a session.""" filters = "filter1" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "filterLineReachability", create=True ) as filterLineReachability: @@ -173,7 +173,7 @@ def test_filter_has_no_unreachable_lines(): def test_filter_has_no_unreachable_lines_from_session(): """Confirm filter-has-no-unreachable-lines assert passes and fails as expected when called from a session.""" filters = "filter1" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "filterLineReachability", create=True ) as filterLineReachability: @@ -192,7 +192,7 @@ def test_filter_has_no_unreachable_lines_from_session(): def test_filter_permits(): """Confirm filter-permits assert passes and fails as expected when specifying a session.""" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "searchFilters", create=True) as mock_search_filters: # Test success mock_search_filters.return_value = MockQuestion() @@ -217,7 +217,7 @@ def test_filter_permits(): def test_filter_permits_from_session(): """Confirm filter-permits assert passes and fails as expected when called from a session.""" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "searchFilters", create=True) as mock_search_filters: # Test success mock_search_filters.return_value = MockQuestion() @@ -243,7 +243,7 @@ def test_flows_fail(): """Confirm flows-fail assert passes and fails as expected when specifying a session.""" startLocation = "node1" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "reachability", create=True) as reachability: # Test success reachability.return_value = MockQuestion() @@ -271,7 +271,7 @@ def test_flows_fail_from_session(): """Confirm flows-fail assert passes and fails as expected when called from a session.""" startLocation = "node1" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "reachability", create=True) as reachability: # Test success reachability.return_value = MockQuestion() @@ -299,7 +299,7 @@ def test_flows_succeed(): """Confirm flows-succeed assert passes and fails as expected when specifying a session.""" startLocation = "node1" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "reachability", create=True) as reachability: # Test success reachability.return_value = MockQuestion() @@ -327,7 +327,7 @@ def test_flows_succeed_from_session(): """Confirm flows-succeed assert passes and fails as expected when called from a session.""" startLocation = "node1" headers = HeaderConstraints(srcIps="1.1.1.1") - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "reachability", create=True) as reachability: # Test success reachability.return_value = MockQuestion() @@ -353,7 +353,7 @@ def test_flows_succeed_from_session(): def test_no_incompatible_bgp_sessions(): """Confirm no-incompatible-bgp-sessions assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "bgpSessionCompatibility", create=True ) as bgpSessionCompatibility: @@ -381,7 +381,7 @@ def test_no_incompatible_bgp_sessions(): def test_no_incompatible_bgp_sessions_from_session(): """Confirm no-incompatible-bgp-sessions assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "bgpSessionCompatibility", create=True ) as bgpSessionCompatibility: @@ -409,7 +409,7 @@ def test_no_incompatible_bgp_sessions_from_session(): def test_no_incompatible_ospf_sessions(): """Confirm no-incompatible-ospf-sessions assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "ospfSessionCompatibility", create=True ) as ospfSessionCompatibility: @@ -441,7 +441,7 @@ def test_no_incompatible_ospf_sessions(): def test_no_incompatible_ospf_sessions_from_session(): """Confirm no-incompatible-ospf-sessions assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "ospfSessionCompatibility", create=True ) as ospfSessionCompatibility: @@ -473,7 +473,7 @@ def test_no_incompatible_ospf_sessions_from_session(): def test_no_unestablished_bgp_sessions(): """Confirm no-uncompatible-bgp-sessions assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "bgpSessionStatus", create=True) as bgpSessionStatus: # Test success bgpSessionStatus.return_value = MockQuestion() @@ -499,7 +499,7 @@ def test_no_unestablished_bgp_sessions(): def test_no_unestablished_bgp_sessions_from_session(): """Confirm no-uncompatible-bgp-sessions assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "bgpSessionStatus", create=True) as bgpSessionStatus: # Test success bgpSessionStatus.return_value = MockQuestion() @@ -525,7 +525,7 @@ def test_no_unestablished_bgp_sessions_from_session(): def test_no_undefined_references(): """Confirm no-undefined-references assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "undefinedReferences", create=True) as undefinedReferences: # Test success undefinedReferences.return_value = MockQuestion() @@ -541,7 +541,7 @@ def test_no_undefined_references(): def test_no_undefined_references_from_session(): """Confirm no-undefined-references assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "undefinedReferences", create=True) as undefinedReferences: # Test success undefinedReferences.return_value = MockQuestion() @@ -557,7 +557,7 @@ def test_no_undefined_references_from_session(): def test_no_duplicate_router_ids_ospf(): """Confirm no-duplicate-router-ids assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "ospfProcessConfiguration", create=True ) as ospfProcessConfiguration: @@ -590,7 +590,7 @@ def test_no_duplicate_router_ids_ospf(): def test_no_duplicate_router_ids_bgp(): """Confirm no-duplicate-router-ids assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "bgpProcessConfiguration", create=True ) as bgpProcessConfiguration: @@ -623,7 +623,7 @@ def test_no_duplicate_router_ids_bgp(): def test_no_duplicate_router_ids_from_session(): """Confirm no-duplicate-router-ids assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object( bf.q, "bgpProcessConfiguration", create=True ) as bgpProcessConfiguration: @@ -656,7 +656,7 @@ def test_no_duplicate_router_ids_from_session(): def test_no_forwarding_loops(): """Confirm no-forwarding-loops assert passes and fails as expected when specifying a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "detectLoops", create=True) as detectLoops: # Test success detectLoops.return_value = MockQuestion() @@ -672,7 +672,7 @@ def test_no_forwarding_loops(): def test_no_forwarding_loops_from_session(): """Confirm no-forwarding-loops assert passes and fails as expected when called from a session.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "detectLoops", create=True) as detectLoops: # Test success detectLoops.return_value = MockQuestion() @@ -689,7 +689,7 @@ def test_no_forwarding_loops_from_session(): def test_get_question_object(): """Confirm _get_question_object identifies the correct question object based on the specified session and the questions it contains.""" # Session contains the question we're searching for - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) with patch.object(bf.q, "qName", create=True): assert bf.q == _get_question_object(bf, "qName") diff --git a/tests/client/test_facts.py b/tests/client/test_facts.py index 8162ba7b..d716422f 100644 --- a/tests/client/test_facts.py +++ b/tests/client/test_facts.py @@ -51,7 +51,7 @@ def answer(self, *args, **kwargs): def test_get_facts_questions(): """Test that get facts calls the right questions, passing through the right args.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) nodes = "foo" with patch.object(bf.q, "nodeProperties", create=True) as mock_node, patch.object( bf.q, "interfaceProperties", create=True @@ -86,7 +86,7 @@ def test_get_facts_questions(): def test_get_facts_questions_specific_snapshot(): """Test that get facts calls the right questions, passing through the right args when a snapshot is specified.""" - bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) + bf = Session(load_questions=False) nodes = "foo" with patch.object(bf.q, "nodeProperties", create=True) as mock_node, patch.object( bf.q, "interfaceProperties", create=True diff --git a/tests/client/test_questions.py b/tests/client/test_questions.py index b1f89cd3..e560a77c 100644 --- a/tests/client/test_questions.py +++ b/tests/client/test_questions.py @@ -50,7 +50,7 @@ def questions(): @pytest.fixture(scope="function") def session(): - s = Session(load_questions=False, use_deprecated_workmgr_v1=False) + s = Session(load_questions=False) yield s diff --git a/tests/client/test_resthelper.py b/tests/client/test_resthelper.py deleted file mode 100644 index a5c3158f..00000000 --- a/tests/client/test_resthelper.py +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2018 The Batfish Open Source Project -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from pybatfish.client.options import Options -from pybatfish.client.resthelper import _adapter, _requests_session - - -def test_session_adapters(): - """Confirm session is configured with correct http and https adapters.""" - http = _requests_session.adapters["http://"] - https = _requests_session.adapters["https://"] - - assert http == _adapter - assert https == _adapter - # Also make sure retries are configured - retries = _adapter.max_retries - assert retries.total == Options.max_retries_to_connect_to_coordinator - assert retries.connect == Options.max_retries_to_connect_to_coordinator - assert retries.read == Options.max_retries_to_connect_to_coordinator - # All request types should be retried - assert not retries.allowed_methods diff --git a/tests/client/test_session.py b/tests/client/test_session.py index 0462b629..b5e7e427 100644 --- a/tests/client/test_session.py +++ b/tests/client/test_session.py @@ -12,13 +12,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import os from unittest.mock import patch import pkg_resources import pytest -from pybatfish.client.session import _PYBF_USE_DEPRECATED_WORKMGR_V1_ENV, Session +from pybatfish.client.session import Session from pybatfish.datamodel import VariableType @@ -55,7 +54,6 @@ def test_get_session(): type_="bf", load_questions=False, host=session_host, - use_deprecated_workmgr_v1=False, ) # Confirm the session is the correct type assert isinstance(session, Session) @@ -66,9 +64,7 @@ def test_get_session(): def test_get_session_default(): """Confirm default Session object is built when no type is specified.""" session_host = "foobar" - session = Session.get( - load_questions=False, host=session_host, use_deprecated_workmgr_v1=False - ) + session = Session.get(load_questions=False, host=session_host) # Confirm the session is the correct type assert isinstance(session, Session) # Confirm params were passed through @@ -87,90 +83,10 @@ def test_get_session_bad(): def test_session_api_key(): """Ensure we use api key from constructor.""" - s = Session(api_key="foo", load_questions=False, use_deprecated_workmgr_v1=False) + s = Session(api_key="foo", load_questions=False) assert s.api_key == "foo" -def test_session_bf_version_not_called_before_checking_v1(): - """Ensure we do not query api version when intializing a Session without v1 override before checking v1""" - with patch("pybatfish.client.restv2helper.get_api_version") as mock_get_api_version: - Session(load_questions=False) - mock_get_api_version.assert_not_called() - - -def test_session_bf_version_called(): - """Ensure we query api version when intializing a Session without v1 override and check v1""" - with patch("pybatfish.client.restv2helper.get_api_version") as mock_get_api_version: - mock_get_api_version.return_value = "2.1.0" - s = Session(load_questions=False) - s.use_deprecated_workmgr_v1() - mock_get_api_version.assert_called_with(s) - - -def test_session_bf_version_use_v1_response(): - """Ensure a session with old Batfish uses WorkMgrV1""" - with patch("pybatfish.client.restv2helper.get_api_version") as mock_get_api_version: - mock_get_api_version.return_value = "2.0.0" - s = Session(load_questions=False) - assert s.use_deprecated_workmgr_v1() - - -def test_session_bf_version_use_only_v2_response(): - """Ensure a session with new or dev Batfish uses WorkMgrV2 only""" - with patch("pybatfish.client.restv2helper.get_api_version") as mock_get_api_version: - mock_get_api_version.return_value = "2.1.0" - s = Session(load_questions=False) - assert not s.use_deprecated_workmgr_v1() - - -def test_session_bf_version_use_v1_arg(): - """Ensure a session with new Batfish uses WorkMgrV1 if forced in Session.__init__""" - with patch( - "pybatfish.client.restv2helper.get_api_version" - ) as mock_get_api_version, patch.dict( - os.environ, {_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV: "0"} - ): - mock_get_api_version.return_value = "2.1.0" - s = Session(load_questions=False, use_deprecated_workmgr_v1=True) - assert s.use_deprecated_workmgr_v1() - - -def test_session_bf_version_use_only_v2_arg(): - """Ensure a session with new Batfish uses only WorkMgrV2 if forced in Session.__init__""" - with patch( - "pybatfish.client.restv2helper.get_api_version" - ) as mock_get_api_version, patch.dict( - os.environ, {_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV: "1"} - ): - mock_get_api_version.return_value = "2.0.0" - s = Session(load_questions=False, use_deprecated_workmgr_v1=False) - assert not s.use_deprecated_workmgr_v1() - - -def test_session_bf_version_use_v1_environ(): - """Ensure a session with new Batfish uses WorkMgrV1 if forced in environment""" - with patch( - "pybatfish.client.restv2helper.get_api_version" - ) as mock_get_api_version, patch.dict( - os.environ, {_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV: "1"} - ): - mock_get_api_version.return_value = "2.1.0" - s = Session(load_questions=False, use_deprecated_workmgr_v1=True) - assert s.use_deprecated_workmgr_v1() - - -def test_session_bf_version_use_only_v2_environ(): - """Ensure a session with new Batfish uses WorkMgrV2 only if forced in environment""" - with patch( - "pybatfish.client.restv2helper.get_api_version" - ) as mock_get_api_version, patch.dict( - os.environ, {_PYBF_USE_DEPRECATED_WORKMGR_V1_ENV: "0"} - ): - mock_get_api_version.return_value = "2.0.0" - s = Session(load_questions=False, use_deprecated_workmgr_v1=False) - assert not s.use_deprecated_workmgr_v1() - - def test_auto_complete_invalid_max_suggestions(): """Ensure auto_complete raises with invalid max suggestions""" s = Session(load_questions=False) diff --git a/tests/client/test_workhelper.py b/tests/client/test_workhelper.py index df31c721..f44a3698 100644 --- a/tests/client/test_workhelper.py +++ b/tests/client/test_workhelper.py @@ -44,7 +44,7 @@ def __execute_and_return_request_params(work_item, session, extra_args=None): def test_execute_request_params(): - session = Session(load_questions=False, use_deprecated_workmgr_v1=False) + session = Session(load_questions=False) # Unmodified work item work_item = WorkItem(session) @@ -119,7 +119,7 @@ def test_print_timestamp(): def test_print_workstatus_fresh_task(caplog): - session = Session(load_questions=False, use_deprecated_workmgr_v1=False) + session = Session(load_questions=False) session.stale_timeout = 5 nowFunction = lambda tzinfo: datetime.datetime( 2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo @@ -151,7 +151,7 @@ def test_print_workstatus_fresh_task(caplog): def test_print_workstatus_fresh_task_subtasks(caplog): - session = Session(load_questions=False, use_deprecated_workmgr_v1=False) + session = Session(load_questions=False) session.stale_timeout = 5 nowFunction = lambda tzinfo: datetime.datetime( 2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo @@ -183,7 +183,7 @@ def test_print_workstatus_fresh_task_subtasks(caplog): def test_print_workstatus_old_task(caplog): - session = Session(load_questions=False, use_deprecated_workmgr_v1=False) + session = Session(load_questions=False) session.stale_timeout = 5 nowFunction = lambda tzinfo: datetime.datetime( 2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo @@ -215,7 +215,7 @@ def test_print_workstatus_old_task(caplog): def test_print_workstatus_old_task_subtasks(caplog): - session = Session(load_questions=False, use_deprecated_workmgr_v1=False) + session = Session(load_questions=False) session.stale_timeout = 5 nowFunction = lambda tzinfo: datetime.datetime( 2017, 12, 20, 0, 0, 0, 0, tzinfo=tzinfo diff --git a/tests/question/test_question.py b/tests/question/test_question.py index 74e06632..62735d9a 100644 --- a/tests/question/test_question.py +++ b/tests/question/test_question.py @@ -49,7 +49,7 @@ @pytest.fixture() def session(): """Session associated with questions created in tests.""" - yield Session(load_questions=False, use_deprecated_workmgr_v1=False) + yield Session(load_questions=False) def test_min_length():