Skip to content

Commit

Permalink
Speed up beacon file reading from zip files in tests (#65)
Browse files Browse the repository at this point in the history
The beacon file is now read from the zip archive and returned as a `BytesIO` object.
Before it would return the file handle from the zip archive which is significantly slower.
  • Loading branch information
yunzheng authored Oct 14, 2024
1 parent c370161 commit 9a8a68f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 18 deletions.
25 changes: 8 additions & 17 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import io
import zipfile
from contextlib import contextmanager
from pathlib import Path

import pytest
Expand Down Expand Up @@ -31,15 +30,14 @@ def my_fixture(request):
beacon_zip_path = testpath / "beacons" / filename
if not beacon_zip_path.exists():
pytest.skip(f"Beacon {beacon_zip_path!r} not found")
with unzip_beacon_as_fh(beacon_zip_path) as beacon_file:
# ZipExtFile.seek() raises io.UnsupportedOperation on Python 3.6
try:
beacon_file.seek(0)
yield beacon_file
except io.UnsupportedOperation:
# fallback to BytesIO
with io.BytesIO(beacon_file.read()) as fh:
yield fh

# Extract the beacon file from the zip archive
with zipfile.ZipFile(beacon_zip_path) as zf:
data = zf.read(beacon_zip_path.stem, pwd=b"dissect.cobaltstrike")

# Return the beacon file as a BytesIO object
with io.BytesIO(data) as fh:
yield fh

return my_fixture

Expand Down Expand Up @@ -86,13 +84,6 @@ def inject_beacon_bconfig_fixture(name):
inject_beacon_bconfig_fixture(name)


@contextmanager
def unzip_beacon_as_fh(zip_file, pwd=b"dissect.cobaltstrike"):
"""Return file object of beacon from zipfile"""
with zipfile.ZipFile(zip_file) as zf:
yield zf.open(zip_file.stem, pwd=pwd)


@pytest.fixture()
def beacon_x64_config_block(beacon_x64_file):
return beacon.BeaconConfig.from_file(beacon_x64_file).config_block
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ envlist = py3,pypy3
[testenv]
usedevelop = true
extras = test
commands = pytest --cov=dissect.cobaltstrike --cov-context=test --cov-report=xml {posargs}
commands = pytest -v --cov=dissect.cobaltstrike --cov-context=test --cov-report=xml {posargs}

[testenv:docs]
extras = docs
Expand Down

0 comments on commit 9a8a68f

Please sign in to comment.