Skip to content

Commit

Permalink
Merge pull request #28 from m4rc1e/contextmanager
Browse files Browse the repository at this point in the history
Add context manager to Local
  • Loading branch information
francisf authored Dec 16, 2020
2 parents 27203ff + 5df90e0 commit 2b85ae3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
14 changes: 11 additions & 3 deletions browserstack/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from browserstack.bserrors import BrowserStackLocalError

class Local:
def __init__(self, key=None, binary_path=None):
def __init__(self, key=None, binary_path=None, **kwargs):
self.key = os.environ['BROWSERSTACK_ACCESS_KEY'] if 'BROWSERSTACK_ACCESS_KEY' in os.environ else key
self.options = None
self.options = kwargs
self.local_logfile_path = os.path.join(os.getcwd(), 'local.log')

def __xstr(self, key, value):
Expand All @@ -29,7 +29,8 @@ def _generate_stop_cmd(self):
return cmd

def start(self, **kwargs):
self.options = kwargs
for k, v in kwargs.items():
self.options[k] = v

if 'key' in self.options:
self.key = self.options['key']
Expand Down Expand Up @@ -74,3 +75,10 @@ def stop(self):
(out, err) = proc.communicate()
except Exception as e:
return

def __enter__(self):
self.start(**self.options)
return self

def __exit__(self, *args):
self.stop()
4 changes: 4 additions & 0 deletions tests/test_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,7 @@ def test_local_identifier(self):
self.local.start(localIdentifier='mytunnel', onlyCommand=True)
self.assertIn('-localIdentifier', self.local._generate_cmd())
self.assertIn('mytunnel', self.local._generate_cmd())

def test_context_manager(self):
with Local('BROWSERSTACK_ACCESS_KEY') as local:
self.assertNotEqual(local.proc.pid, 0)

0 comments on commit 2b85ae3

Please sign in to comment.