def vcr(vcr):
    def range_header_matcher(r1, r2):
        return r1.headers.get("Range", "") == r2.headers.get("Range", "")

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix(".yaml")
    vcr.filter_headers = ["Set-Cookie"]
    vcr.before_record_request = scrub_request
    vcr.before_record_response = chain(
        scrub_response,
        scrub_string(rb"Request done in \S+ seconds.",
                     b"Request done in ... seconds."),
        scrub_string(rb'"updated":"[^"]+"', b'"updated":"..."'),
        scrub_string(rb'totalResults":"\d{4,}"', b'totalResults":"10000"'),
        scrub_string(rb"of \d{4,} total results", b"of 10000 total results"),
        scrub_string(rb"&start=\d{4,}&rows=0", b"&start=10000&rows=0"),
    )
    vcr.decode_compressed_response = True
    vcr.register_serializer("custom", BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = "custom"
    vcr.register_matcher("range_header", range_header_matcher)
    vcr.match_on = [
        "method", "range_header", "host", "port", "path", "query", "body"
    ]
    return vcr
Beispiel #2
0
def vcr(vcr):
    def scrub_request(request):
        for header in ("Authorization", "Set-Cookie", "Cookie"):
            if header in request.headers:
                del request.headers[header]
        return request

    def scrub_response(response):
        for header in ("Authorization", "Set-Cookie", "Cookie", "Date", "Expires", "Transfer-Encoding"):
            if header in response["headers"]:
                del response["headers"][header]
        return response

    def range_header_matcher(r1, r2):
        return r1.headers.get('Range', '') == r2.headers.get('Range', '')

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix('.yaml')
    vcr.filter_headers = ['Set-Cookie']
    vcr.before_record_request = scrub_request
    vcr.before_record_response = scrub_response
    vcr.decode_compressed_response = True
    vcr.register_serializer('custom', BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = 'custom'
    vcr.register_matcher('range_header', range_header_matcher)
    vcr.match_on = ['uri', 'method', 'body', 'range_header']
    return vcr
Beispiel #3
0
def vcr(vcr):
    def scrub_request(request):
        for header in ("Authorization", "Set-Cookie", "Cookie"):
            if header in request.headers:
                del request.headers[header]
        return request

    def scrub_response(response):
        for header in ("Authorization", "Set-Cookie", "Cookie", "Date",
                       "Expires", "Transfer-Encoding"):
            if header in response["headers"]:
                del response["headers"][header]
        return response

    def range_header_matcher(r1, r2):
        return r1.headers.get('Range', '') == r2.headers.get('Range', '')

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix('.yaml')
    vcr.filter_headers = ['Set-Cookie']
    vcr.before_record_request = scrub_request
    vcr.before_record_response = scrub_response
    vcr.decode_compressed_response = True
    vcr.register_serializer('custom', BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = 'custom'
    vcr.register_matcher('range_header', range_header_matcher)
    vcr.match_on = ['uri', 'method', 'body', 'range_header']
    return vcr
Beispiel #4
0
def vcr_config():
    """VCR configuration."""
    return {
        "cassette_library_dir": "gencove/tests/upload/vcr",
        "filter_headers": [
            "Authorization",
            "Content-Length",
            "User-Agent",
            "X-Amz-Security-Token",
            "X-Amz-Date",
        ],
        "filter_post_data_parameters": [
            ("email", "*****@*****.**"),
            ("password", "mock_password"),
        ],
        "filter_query_parameters": [
            ("search", "gncv://cli-mock/test.fastq.gz")
        ],
        "match_on": ["method", "scheme", "port", "path", "query"],
        "path_transformer": VCR.ensure_suffix(".yaml"),
        "before_record_request": [
            replace_gencove_url_vcr,
            filter_upload_request,
            filter_project_samples_request,
        ],
        "before_record_response": [
            filter_jwt,
            filter_upload_credentials_response,
            filter_upload_post_data_response,
            filter_volatile_dates,
            filter_aws_headers,
            filter_sample_sheet_response,
            filter_project_samples_response,
        ],
    }
Beispiel #5
0
 def _get_vcr(self, **kwargs):
     my_vcr = super(GoogleSheetsConfigTestApi, self)._get_vcr(**kwargs)
     my_vcr.record_mode = 'once'
     my_vcr.path_transformer = VCR.ensure_suffix('.yaml')
     my_vcr.cassette_library_dir = os.path.dirname(
         os.path.abspath(__file__)) + '/vcr/google_sheets/'
     return my_vcr
Beispiel #6
0
def make_vcr(pytestconfig, cassette_library_dir):
    mode = pytestconfig.getoption('--vcr-mode')
    api_key = pytestconfig.getoption('--whispir-api-key')
    username = pytestconfig.getoption('--whispir-username')
    gcm_api_key = pytestconfig.getoption('--whispir-gcm-api-key')
    scrubber = scrub_patterns(
        ((api_key, TEST_API_KEY), (username, TEST_USERNAME),
         (gcm_api_key, TEST_GCM_API_KEY)))
    options = {
        'record_mode':
        mode,
        'filter_headers': [('authorization', replace_auth),
                           ('set-cookie', None), ('cookie', None),
                           ('User-Agent', None), ('x-api-key', TEST_API_KEY)],
        'before_record_response':
        scrubber,
        'before_record_request':
        scrubber,
        'path_transformer':
        VCR.ensure_suffix('.yaml'),
        'decode_compressed_response':
        True,
        'cassette_library_dir':
        cassette_library_dir,
        'match_on':
        ('method', 'scheme', 'host', 'port', 'path', 'query', 'headers'),
        'serializer':
        'pretty-yaml'
    }
    vcr = VCR(**options)
    vcr.register_serializer('pretty-yaml', prettyserializer)
    return vcr
Beispiel #7
0
def test_ensure_suffix():
    vcr = VCR(inject_cassette=True, path_transformer=VCR.ensure_suffix('.yaml'))
    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join(os.path.dirname(__file__),
                                              'function_name.yaml')
    function_name()
Beispiel #8
0
def vcr(vcr):
    def scrub_request(request):
        for header in ("Authorization", "Set-Cookie", "Cookie"):
            if header in request.headers:
                del request.headers[header]
        return request

    def scrub_response(response):
        for header in (
                "Authorization",
                "Set-Cookie",
                "Cookie",
                "Date",
                "Expires",
                "Transfer-Encoding",
        ):
            if header in response["headers"]:
                del response["headers"][header]
        return response

    def range_header_matcher(r1, r2):
        return r1.headers.get("Range", "") == r2.headers.get("Range", "")

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix(".yaml")
    vcr.filter_headers = ["Set-Cookie"]
    vcr.before_record_request = scrub_request
    vcr.before_record_response = scrub_response
    vcr.decode_compressed_response = True
    vcr.register_serializer("custom", BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = "custom"
    vcr.register_matcher("range_header", range_header_matcher)
    vcr.match_on = ["uri", "method", "body", "range_header"]
    return vcr
def vcr_config():
    """VCR configuration."""
    return {
        "cassette_library_dir":
        "gencove/tests/projects/vcr",
        "filter_headers": [
            "Authorization",
            "Content-Length",
            "User-Agent",
        ],
        "filter_post_data_parameters": [
            ("email", "*****@*****.**"),
            ("password", "mock_password"),
        ],
        "match_on": ["method", "scheme", "port", "path", "query"],
        "path_transformer":
        VCR.ensure_suffix(".yaml"),
        "before_record_request": [
            replace_gencove_url_vcr,
            filter_project_delete_samples,
        ],
        "before_record_response": [
            filter_jwt,
            filter_volatile_dates,
        ],
    }
Beispiel #10
0
def vcr_config():
    return {
        "record_mode": "new_episodes",  # "once",
        "cassette_library_dir": "tests/cassettes",
        "path_transformer": VCR.ensure_suffix(".yaml"),
        "before_record_request": filter_request,
        "before_record_response": filter_response,
    }
Beispiel #11
0
def vcr():
    return VCR(
        cassette_library_dir=str(
            Path(__file__).parent.joinpath("fixtures/cassettes")),
        decode_compressed_response=True,
        path_transformer=VCR.ensure_suffix(".yaml"),
        record_mode="once",
        filter_headers=["authorization"],
    )
Beispiel #12
0
def test_ensure_suffix():
    vcr = VCR(inject_cassette=True, path_transformer=VCR.ensure_suffix('.yaml'))

    @vcr.use_cassette
    def function_name(cassette):
        assert cassette._path == os.path.join(os.path.dirname(__file__),
                                              'function_name.yaml')

    function_name()
Beispiel #13
0
 def _get_vcr(self, **kwargs):
     my_vcr = super(DojoVCRTestCase, self)._get_vcr(**kwargs)
     my_vcr.record_mode = 'once'
     my_vcr.path_transformer = VCR.ensure_suffix('.yaml')
     my_vcr.filter_headers = ['Authorization', 'X-Atlassian-Token']
     my_vcr.cassette_library_dir = get_unit_tests_path() + '/vcr/jira/'
     # filters headers doesn't seem to work for cookies, so use callbacks to filter cookies from being recorded
     my_vcr.before_record_request = self.before_record_request
     my_vcr.before_record_response = self.before_record_response
     return my_vcr
Beispiel #14
0
def custom_vcr():
    dirname = os.path.dirname(__file__)
    return VCR(decode_compressed_response=True,
               cassette_library_dir=os.path.join(dirname,
                                                 'fixtures/cassettes'),
               path_transformer=VCR.ensure_suffix('.yml'),
               filter_query_parameters=bad_fields,
               before_record_response=filter_payload,
               filter_post_data_parameters=bad_fields,
               match_on=['path', 'method'])
Beispiel #15
0
def get_recorder(**kw):
    defaults = dict(
        record_mode='once',
        cassette_library_dir=join(dirname(__file__), 'fixtures/cassettes'),
        path_transformer=VCR.ensure_suffix('.yaml'),
        match_on=['method', 'path', 'query'],
        filter_headers=['Authorization'],
        decode_compressed_response=True,
    )
    defaults.update(kw)
    return VCR(**defaults)
def get_recorder(base_path=None, **kw):
    base_path = base_path or dirname(__file__)
    defaults = dict(
        record_mode="once",
        cassette_library_dir=join(base_path, "fixtures/cassettes"),
        path_transformer=VCR.ensure_suffix(".yaml"),
        match_on=["method", "path", "query"],
        filter_headers=["Authorization"],
        decode_compressed_response=True,
    )
    defaults.update(kw)
    return VCR(**defaults)
Beispiel #17
0
 def _decorate_test(self, test_path):
     recorder = VCR(
         before_record_request=self._before_record,
         record_mode=os.environ.get('VCR_MODE', 'none'),
         cassette_library_dir=join(test_path, 'fixtures/cassettes'),
         path_transformer=VCR.ensure_suffix('.yaml'),
         filter_headers=['Authorization'],
     )
     for test_func in dir(self):
         if test_func.startswith('test'):
             setattr(self, test_func,
                     recorder.use_cassette(getattr(self, test_func)))
Beispiel #18
0
def vcr(request):
    defaults = ["method", "scheme", "host", "port", "path", "query"]
    defaults += request.getfixturevalue("vcr_match_on")

    # record_mode = {once, new_episodes, none, all}
    # https://vcrpy.readthedocs.io/en/latest/usage.html#record-modes
    return VCR(
        filter_headers=request.getfixturevalue("vcr_headers_filter"),
        record_mode=os.environ.get("VCR_MODE", "once"),
        cassette_library_dir="tests/fixtures/vcr",
        match_on=defaults,
        path_transformer=VCR.ensure_suffix(".yaml"),
    )
Beispiel #19
0
def vcr(request, vcr_config):
    """The VCR instance"""
    kwargs = dict(
        path_transformer=VCR.ensure_suffix(".yaml"),
    )
    marker = request.node.get_marker('vcr')
    record_mode = request.config.getoption('--vcr-record-mode')

    kwargs.update(vcr_config)
    if marker:
        kwargs.update(marker.kwargs)
    if record_mode:
        kwargs['record_mode'] = record_mode

    vcr = VCR(**kwargs)
    return vcr
Beispiel #20
0
def build_vcr(path=None, **kwargs):
    cassette_library_dir = BASE_CASSETTE_LIBRARY_DIR
    if path:
        cassette_library_dir += '/' + path

    settings = dict(
        serializer='yaml',
        cassette_library_dir=cassette_library_dir,
        record_mode='once',
        inject_cassette=True,
        path_transformer=VCR.ensure_suffix('.yml'),
        decode_compressed_response=True,
        filter_headers=[('authorization', '<AUTHORIZATION-HEADER>')],
        match_on=['method', 'scheme', 'host', 'port', 'path', 'query', 'body'],
    )
    settings.update(**kwargs)
    return VCR(**settings)
Beispiel #21
0
    def __new__(cls, name, bases, members):
        test_path = members['_test_path']

        # decorate test method with the cassette
        klass = type.__new__(cls, name, bases, members)
        for name, val in inspect.getmembers(klass, inspect.ismethod):
            if name.startswith('test'):
                recorder = VCR(
                    before_record_request=_before_record,
                    record_mode=os.environ.get('VCR_MODE', 'none'),
                    cassette_library_dir=join(test_path, 'fixtures/cassettes'),
                    path_transformer=VCR.ensure_suffix('.yaml'),
                    filter_headers=['Authorization'],
                )
                val = recorder.use_cassette(val)
                setattr(klass, name, val)
        return klass
Beispiel #22
0
def vcr(
    request,
    vcr_config,
    vcr_cassette_dir,
):
    """The VCR instance"""
    if request.config.getoption('--vcr-record-mode'):
        warnings.warn(
            "--vcr-record-mode has been deprecated and will be removed in a future "
            "release. Use --vcr-record instead.", DeprecationWarning)
    kwargs = dict(
        cassette_library_dir=vcr_cassette_dir,
        path_transformer=VCR.ensure_suffix(".yaml"),
    )
    kwargs.update(vcr_config)
    _update_kwargs(request, kwargs)
    vcr = VCR(**kwargs)
    return vcr
Beispiel #23
0
def vcr_session(request):
    """Setup VCR at session-level.

    Borrowed from python-vcr.
    """
    test_dir = os.path.abspath(os.path.dirname(__file__))
    cassette_dir = os.path.join(test_dir, 'cassettes')
    kwargs = dict(cassette_library_dir=cassette_dir,
                  path_transformer=VCR.ensure_suffix(".yaml"))
    record_mode = request.config.getoption('--vcr-record')
    if record_mode:
        kwargs['record_mode'] = record_mode
    if request.config.getoption('--disable-vcr'):
        # Set mode to record but discard all responses to disable both recording and playback
        kwargs['record_mode'] = 'new_episodes'
        kwargs['before_record_response'] = lambda *args, **kwargs: None
    vcr = VCR(**kwargs)
    yield vcr
Beispiel #24
0
def recorder(request):
    """Generate and start a recorder using a helium.Client."""
    cassette_name = ''

    if request.module is not None:
        cassette_name += request.module.__name__ + '.'

    cassette_name += request.function.__name__

    recorder = VCR(
        cassette_library_dir=RECORD_FOLDER,
        decode_compressed_response=True,
        path_transformer=VCR.ensure_suffix('.yml'),
        filter_headers=['Authorization'],
        match_on=['uri', 'method'],
    )
    cassette = recorder.use_cassette(path=cassette_name)
    with cassette:
        yield recorder
Beispiel #25
0
def vcr(vcr):
    def scrub_request(request):
        for header in ("Authorization", "Set-Cookie", "Cookie"):
            if header in request.headers:
                del request.headers[header]
        return request

    def scrub_response(response):
        ignore = set(x.lower() for x in [
            "Authorization",
            "Set-Cookie",
            "Cookie",
            "Date",
            "Expires",
        ])
        for header in list(response["headers"]):
            if header.lower() in ignore or header.lower().startswith(
                    "access-control"):
                del response["headers"][header]
        return response

    def range_header_matcher(r1, r2):
        return r1.headers.get("Range", "") == r2.headers.get("Range", "")

    vcr.cassette_library_dir = CASSETTE_DIR
    vcr.path_transformer = VCR.ensure_suffix(".yaml")
    vcr.filter_headers = ["Set-Cookie"]
    vcr.before_record_request = scrub_request
    vcr.before_record_response = scrub_response
    vcr.decode_compressed_response = True
    vcr.register_serializer("custom", BinaryContentSerializer(CASSETTE_DIR))
    vcr.serializer = "custom"
    vcr.register_matcher("range_header", range_header_matcher)
    vcr.match_on = [
        "method", "range_header", "host", "port", "path", "query", "body"
    ]
    return vcr
from sentry_youtrack.configuration import YouTrackConfiguration
from unittest import TestCase
from vcr import VCR
import os

vcr = VCR(path_transformer=VCR.ensure_suffix('.yaml'),
          cassette_library_dir=os.path.join('tests', 'cassettes'))
print(os.path.join('tests', 'cassettes'))


class TestYouTrackConfiguration(TestCase):
    def setUp(self):
        self.url = 'https://youtrack.myjetbrains.com'
        self.username = '******'
        self.password = '******'
        self.invalid_url = 'https://example.youtrack.example'

    def assert_fields_equal(self, field_names, config):
        assert sorted([field['name']
                       for field in config]) == sorted(field_names)

    def get_field(self, yt_config, field_name):
        for field in yt_config.config:
            if field['name'] == field_name:
                return field
        return None

    def test_renders_no_input(self):
        yt_config = YouTrackConfiguration({})
        self.assert_fields_equal(['password', 'url', 'username'],
                                 yt_config.config)
Vim�UnDo�('D��'-�Eԕ^͈D�,���*/�v^5��4L        self.assertEquals(Decimal("0.000039080000000000"), coin.btc_per_day)+">>>>^���_�����^�b���5�_�����^�b��5�_�%����^�c�	;Sfrom coinmine.coin.services.minerstat.coin_per_day_updater import CoinPerDayUpdater5�_�)
����^�c��(*;,    def test_handshake_per_day_update(self):5�_�/
����^�c��.0;'    def test_grin_per_day_update(self):5�_�5
����^�c��46;M    def test_update_skips_update_if_results_missing(self, mocked_per_day_gw):5�_�1!����^�c��02;M        self.assertEquals(Decimal("0.453569400000000011"), coin.coin_per_day)�12;5�_�	18����^�c��02;c        self.assertEquals(Decimal('0.570524000000000000'"0.453569400000000011"), coin.coin_per_day)5�_�
	+!����^�c��*,;M        self.assertEquals(Decimal("1.218043290399940748"), coin.coin_per_day)�+,;5�_�	
+8����^�c��*,;c        self.assertEquals(Decimal('0.320934000000000000'"1.218043290399940748"), coin.coin_per_day)5�_�
+9����^�c��*,;N        self.assertEquals(Decimal('0.320934000000000000'"), coin.coin_per_day)5�_�
+7����^�c��; from django.test import TestCasefrom decimal import Decimalfrom vcr import VCRfrom pathlib import Pathfrom unittest.mock import patch%from coinmine.coin.models import CoinTfrom coinmine.coin.services.whattomine.coin_per_day_updater import CoinPerDayUpdater
my_vcr = VCR(0    path_transformer=VCR.ensure_suffix(".yaml"),J    cassette_library_dir="{}/vcr_cassettes".format(Path(__file__).parent),    record_mode="once",)'class CoinPerDayUpdaterTests(TestCase):    fixtures = ["coins.yaml"]    def setUp(self):D        # ATTN: if you plan to change hashrate, re-record VCR (once)5        Coin.objects.filter(short_name="hns").update(D            estimated_hashrate=60, coin_per_day="0", btc_per_day="0"	        )6        Coin.objects.filter(short_name="grin").update(E            estimated_hashrate=0.6, coin_per_day="0", btc_per_day="0"	        )H        self.coins = Coin.objects.filter(short_name__in=["hns", "grin"])        for coin in self.coins:>            self.assertEquals(Decimal("0"), coin.coin_per_day)=            self.assertEquals(Decimal("0"), coin.btc_per_day)6    def _get_coin_after_update(self, coin_short_name):9        coin = self.coins.get(short_name=coin_short_name)&        CoinPerDayUpdater.update(coin)        coin.refresh_from_db()        return coin    @my_vcr.use_cassette7    def test_whattomine_handshake_per_day_update(self):1        coin = self._get_coin_after_update("hns")M        self.assertEquals(Decimal('0.320934000000000000'), coin.coin_per_day)L        self.assertEquals(Decimal("0.000048154732464316"), coin.btc_per_day)    @my_vcr.use_cassette2    def test_whattomine_grin_per_day_update(self):2        coin = self._get_coin_after_update("grin")M        self.assertEquals(Decimal('0.570524000000000000'), coin.coin_per_day)L        self.assertEquals(Decimal("0.000052213267406772"), coin.btc_per_day)H    @patch("coinmine.coin.apis.minerstat.per_day.PerDayGateway.to_dict")X    def test_whattomine_update_skips_update_if_results_missing(self, mocked_per_day_gw):        # return empty results+        mocked_per_day_gw.return_value = {}1        coin = self._get_coin_after_update("hns"):        self.assertEquals(Decimal("0"), coin.coin_per_day)9        self.assertEquals(Decimal("0"), coin.btc_per_day)5�_�
2"����^�d��13;L        self.assertEquals(Decimal("0.000052213267406772"), coin.btc_per_day)�23;5�_�
29����^�d��13;b        self.assertEquals(Decimal("'0.000039080000000000'0.000052213267406772"), coin.btc_per_day)5�_�2:����^�d��13;N        self.assertEquals(Decimal("'0.000039080000000000'"), coin.btc_per_day)5�_�2"����^�d��13;M        self.assertEquals(Decimal("'0.000039080000000000'), coin.btc_per_day)5�_�2!����^�d��13;L        self.assertEquals(Decimal('0.000039080000000000'), coin.btc_per_day)�23;5�_�28����^�d��13;b        self.assertEquals(Decimal('0.000008000000000000''0.000039080000000000'), coin.btc_per_day)5�_�29����^�d��13;M        self.assertEquals(Decimal('0.000008000000000000''), coin.btc_per_day)5�_�27����^�d��; from django.test import TestCasefrom decimal import Decimalfrom vcr import VCRfrom pathlib import Pathfrom unittest.mock import patch%from coinmine.coin.models import CoinTfrom coinmine.coin.services.whattomine.coin_per_day_updater import CoinPerDayUpdater
my_vcr = VCR(0    path_transformer=VCR.ensure_suffix(".yaml"),J    cassette_library_dir="{}/vcr_cassettes".format(Path(__file__).parent),    record_mode="once",)'class CoinPerDayUpdaterTests(TestCase):    fixtures = ["coins.yaml"]    def setUp(self):D        # ATTN: if you plan to change hashrate, re-record VCR (once)5        Coin.objects.filter(short_name="hns").update(D            estimated_hashrate=60, coin_per_day="0", btc_per_day="0"	        )6        Coin.objects.filter(short_name="grin").update(E            estimated_hashrate=0.6, coin_per_day="0", btc_per_day="0"	        )H        self.coins = Coin.objects.filter(short_name__in=["hns", "grin"])        for coin in self.coins:>            self.assertEquals(Decimal("0"), coin.coin_per_day)=            self.assertEquals(Decimal("0"), coin.btc_per_day)6    def _get_coin_after_update(self, coin_short_name):9        coin = self.coins.get(short_name=coin_short_name)&        CoinPerDayUpdater.update(coin)        coin.refresh_from_db()        return coin    @my_vcr.use_cassette7    def test_whattomine_handshake_per_day_update(self):1        coin = self._get_coin_after_update("hns")M        self.assertEquals(Decimal("0.320934000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal("0.000048154732464316"), coin.btc_per_day)    @my_vcr.use_cassette2    def test_whattomine_grin_per_day_update(self):2        coin = self._get_coin_after_update("grin")M        self.assertEquals(Decimal("0.570524000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal('0.000008000000000000'), coin.btc_per_day)H    @patch("coinmine.coin.apis.minerstat.per_day.PerDayGateway.to_dict")X    def test_whattomine_update_skips_update_if_results_missing(self, mocked_per_day_gw):        # return empty results+        mocked_per_day_gw.return_value = {}1        coin = self._get_coin_after_update("hns"):        self.assertEquals(Decimal("0"), coin.coin_per_day)9        self.assertEquals(Decimal("0"), coin.btc_per_day)5�_�2!����^�e'�13;L        self.assertEquals(Decimal("0.000008000000000000"), coin.btc_per_day)�23;5�_�28����^�e)�13;b        self.assertEquals(Decimal('0.000039080000000000'"0.000008000000000000"), coin.btc_per_day)5�_�29����^�e*�13;M        self.assertEquals(Decimal('0.000039080000000000'"), coin.btc_per_day)5�_�,!����^�e:�+-;L        self.assertEquals(Decimal("0.000048154732464316"), coin.btc_per_day)�,-;5�_�,8����^�e;�+-;b        self.assertEquals(Decimal('0.000008000000000000'"0.000048154732464316"), coin.btc_per_day)5�_�,8����^�e<�; from django.test import TestCasefrom decimal import Decimalfrom vcr import VCRfrom pathlib import Pathfrom unittest.mock import patch%from coinmine.coin.models import CoinTfrom coinmine.coin.services.whattomine.coin_per_day_updater import CoinPerDayUpdater
my_vcr = VCR(0    path_transformer=VCR.ensure_suffix(".yaml"),J    cassette_library_dir="{}/vcr_cassettes".format(Path(__file__).parent),    record_mode="once",)'class CoinPerDayUpdaterTests(TestCase):    fixtures = ["coins.yaml"]    def setUp(self):D        # ATTN: if you plan to change hashrate, re-record VCR (once)5        Coin.objects.filter(short_name="hns").update(D            estimated_hashrate=60, coin_per_day="0", btc_per_day="0"	        )6        Coin.objects.filter(short_name="grin").update(E            estimated_hashrate=0.6, coin_per_day="0", btc_per_day="0"	        )H        self.coins = Coin.objects.filter(short_name__in=["hns", "grin"])        for coin in self.coins:>            self.assertEquals(Decimal("0"), coin.coin_per_day)=            self.assertEquals(Decimal("0"), coin.btc_per_day)6    def _get_coin_after_update(self, coin_short_name):9        coin = self.coins.get(short_name=coin_short_name)&        CoinPerDayUpdater.update(coin)        coin.refresh_from_db()        return coin    @my_vcr.use_cassette7    def test_whattomine_handshake_per_day_update(self):1        coin = self._get_coin_after_update("hns")M        self.assertEquals(Decimal("0.320934000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal('0.000008000000000000'), coin.btc_per_day)    @my_vcr.use_cassette2    def test_whattomine_grin_per_day_update(self):2        coin = self._get_coin_after_update("grin")M        self.assertEquals(Decimal("0.570524000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal('0.000039080000000000'), coin.btc_per_day)H    @patch("coinmine.coin.apis.minerstat.per_day.PerDayGateway.to_dict")X    def test_whattomine_update_skips_update_if_results_missing(self, mocked_per_day_gw):        # return empty results+        mocked_per_day_gw.return_value = {}1        coin = self._get_coin_after_update("hns"):        self.assertEquals(Decimal("0"), coin.coin_per_day)9        self.assertEquals(Decimal("0"), coin.btc_per_day)5�_�4(����^�eb�35;H    @patch("coinmine.coin.apis.minerstat.per_day.PerDayGateway.to_dict")5�_�4����^�ei�35;?    @patch("coinmine.coin.apis..per_day.PerDayGateway.to_dict")5�_�!����!&V^�o[� !6    def _get_coin_after_update(self, coin_short_name):9        coin = self.coins.get(short_name=coin_short_name)&        CoinPerDayUpdater.update(coin)        coin.refresh_from_db()        return coin5�_� ����!!V^�ov�Tfrom coinmine.coin.services.whattomine.coin_per_day_updater import CoinPerDayUpdater5�_�! ����  V^�o|�	5�	45�_� "!���� 7V7^�o��        for coin in self.coins:>            self.assertEquals(Decimal("0"), coin.coin_per_day)=            self.assertEquals(Decimal("0"), coin.btc_per_day)5�_�!#"����7V7^�o��2        �15�_�"$#����7V7^�o��39        TestHelpers._assert_coins_set_to_zero(self.coins)5�_�#%$"����7V7^�p$	�!#31        coin = self._get_coin_after_update("hns")5�_�$&%"1����7V7^�pL�!#3S        coin = TestHelpers.get_coin_after_update(self._get_coin_after_update("hns")5�_�%'&"2����7V7^�pM
�!#38        coin = TestHelpers.get_coin_after_update(("hns")5�_�&('(0����7V7^�pQ�(*3�()35�_�')((����7V7^�pR�'(2        coin = self._get_coin_after_update("grin")5�_�(*)(5����7V7^�pT�')37        coin = TestHelpers.get_coin_after_update("hns")5�_�)+*10����7V7^�pX�133�1235�_�*,+1����7V7^�pX�011        coin = self._get_coin_after_update("hns")5�_�+-,16����7V7^�p[�0238        coin = TestHelpers.get_coin_after_update("grin")5�_�,.-����7V7^�p�
�	38from coinmine.coin.tests.test_helpers import TestHelpers5�_�-/.����7V7^�p��38        TestHelpers.assert_coins_set_to_zero(self.coins)5�_�.0/����7V7^�rK�
3�	35�_�/10	%����  7V7^�rN�
4Sfrom coinmine.coin.services.minerstat.coin_per_day_updater import CoinPerDayUpdater5�_�021#1����  7V7^�rU�"$47        coin = TestHelpers.get_coin_after_update("hns")5�_�132)1����  7V7^�rY�(*48        coin = TestHelpers.get_coin_after_update("grin")5�_�24321����  7V7^�r]�1347        coin = TestHelpers.get_coin_after_update("hns")5�_�3542B����  7V7^�r]�4 from django.test import TestCasefrom decimal import Decimalfrom vcr import VCRfrom pathlib import Pathfrom unittest.mock import patch%from coinmine.coin.models import CoinAfrom coinmine.coin.tests.services.test_helpers import TestHelpersTfrom coinmine.coin.services.whattomine.coin_per_day_updater import CoinPerDayUpdater
my_vcr = VCR(0    path_transformer=VCR.ensure_suffix(".yaml"),J    cassette_library_dir="{}/vcr_cassettes".format(Path(__file__).parent),    record_mode="once",)'class CoinPerDayUpdaterTests(TestCase):    fixtures = ["coins.yaml"]    def setUp(self):D        # ATTN: if you plan to change hashrate, re-record VCR (once)5        Coin.objects.filter(short_name="hns").update(D            estimated_hashrate=60, coin_per_day="0", btc_per_day="0"	        )6        Coin.objects.filter(short_name="grin").update(E            estimated_hashrate=0.6, coin_per_day="0", btc_per_day="0"	        )H        self.coins = Coin.objects.filter(short_name__in=["hns", "grin"]):        TestHelpers().assert_coins_set_to_zero(self.coins)    @my_vcr.use_cassette7    def test_whattomine_handshake_per_day_update(self):I        coin = TestHelpers.get_coin_after_update(CoinPerDayUpdater,"hns")M        self.assertEquals(Decimal("0.320934000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal("0.000008000000000000"), coin.btc_per_day)    @my_vcr.use_cassette2    def test_whattomine_grin_per_day_update(self):J        coin = TestHelpers.get_coin_after_update(CoinPerDayUpdater,"grin")M        self.assertEquals(Decimal("0.570524000000000000"), coin.coin_per_day)L        self.assertEquals(Decimal("0.000039080000000000"), coin.btc_per_day)I    @patch("coinmine.coin.apis.whattomine.per_day.PerDayGateway.to_dict")X    def test_whattomine_update_skips_update_if_results_missing(self, mocked_per_day_gw):        # return empty results+        mocked_per_day_gw.return_value = {}I        coin = TestHelpers.get_coin_after_update(CoinPerDayUpdater,"hns"):        self.assertEquals(Decimal("0"), coin.coin_per_day)9        self.assertEquals(Decimal("0"), coin.btc_per_day)5�_�465*"����^���)+4M        self.assertEquals(Decimal("0.570524000000000000"), coin.coin_per_day)�*+45�_�576*7����^����)+4a        self.assertEquals(Decimal("0.5799810000000000000.570524000000000000"), coin.coin_per_day)5�_�687$"����^����#%4M        self.assertEquals(Decimal("0.320934000000000000"), coin.coin_per_day)�$%45�_�798$7����^����#%4a        self.assertEquals(Decimal("0.4044660000000000000.320934000000000000"), coin.coin_per_day)5�_�8:9%"����^����$&4L        self.assertEquals(Decimal("0.000008000000000000"), coin.btc_per_day)�%&45�_�9;:%7����^����$&4`        self.assertEquals(Decimal("0.0000407600000000000.000008000000000000"), coin.btc_per_day)5�_�:<;%"����^����$&4L        self.assertEquals(Decimal("0.000040760000000000"), coin.btc_per_day)�%&45�_�;=<%7����^����$&4`        self.assertEquals(Decimal("0.0000099500000000000.000040760000000000"), coin.btc_per_day)5�_�<>=+"����^����*,4L        self.assertEquals(Decimal("0.000039080000000000"), coin.btc_per_day)�+,45�_�=>+7����^����*,4`        self.assertEquals(Decimal("0.0000407600000000000.000039080000000000"), coin.btc_per_day)5�_�,"����^�e9�,-;�+-;b        self.assertEquals(Decimal("'0.000008000000000000'0.000048154732464316"), coin.btc_per_day)5��
Beispiel #28
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_urltitle
from utils import check_re

import pytest
from vcr import VCR

my_vcr = VCR(
    path_transformer=VCR.ensure_suffix(".yaml"),
    cassette_library_dir="tests/cassettes/",
    record_mode=pytest.config.getoption("--vcrmode"),
)

logging.basicConfig()  # you need to initialize logging, otherwise you will not see anything from vcrpy
vcr_log = logging.getLogger("vcr")
vcr_log.setLevel(logging.DEBUG)


@pytest.fixture
def botmock():
    bot = bot_mock.BotMock()
    module_urltitle.init(bot)
    return bot


lengh_str_regex = r"\d+(h|m|s)(\d+(m))?(\d+s)?"
views_str_regex = r"\d+(\.\d+)?(k|M|Billion|Trillion)?"
Beispiel #29
0
from vcr import VCR


def before_record_callback(request):
    """Replace confidential information in the recorded cassettes.

    - customer:key are replaced with 'X:Y'

    """
    payload = json.loads(request.body)
    payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y'
    request.body = json.dumps(payload)
    return request


my_vcr = VCR(serializer='json',
             record_mode='once',
             cassette_library_dir=join(dirname(__file__), 'cassettes'),
             path_transformer=VCR.ensure_suffix('.json'),
             before_record=before_record_callback)


def fixture_path(filename):
    """Build the full path of a fixture file."""
    return join(dirname(__file__), 'fixtures', filename)


class BaseCase(unittest.TestCase):
    pass
Beispiel #30
0
    """
    body = request.body
    if helpers.PY3:
        body = request.body.decode('utf-8')

    payload = json.loads(body)
    payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y'
    request.body = json.dumps(payload)
    return request


my_vcr = VCR(
    serializer='json',
    record_mode='once',
    cassette_library_dir=join(dirname(__file__), 'cassettes'),
    path_transformer=VCR.ensure_suffix('.json'),
    before_record=before_record_callback
)

if helpers.PY3:
    my_vcr.register_serializer('json', JSONSerializer)


def fixture_path(filename):
    """Build the full path of a fixture file."""
    return join(dirname(__file__), 'fixtures', filename)


class BaseCase(unittest.TestCase):
    pass
Beispiel #31
0
    def serialize(cassette_dict):
        cassette_dict["recorded_at"] = datetime.now().isoformat()[:-7]
        return (
            f"{json.dumps(serialize_dict(cassette_dict), sort_keys=True, indent=2)}\n"
        )

    @staticmethod
    def deserialize(cassette_string):
        return json.loads(cassette_string)


vcr = VCR(
    before_record_response=filter_access_token,
    cassette_library_dir="tests/integration/cassettes",
    match_on=["uri", "method"],
    path_transformer=VCR.ensure_suffix(".json"),
    serializer="custom_serializer",
)
vcr.register_serializer("custom_serializer", CustomSerializer)
vcr.register_persister(CustomPersister)


def after_init(func, *args):
    func(*args)


def add_init_hook(original_init):
    """Wrap an __init__ method to also call some hooks."""

    @wraps(original_init)
    def wrapper(self, *args, **kwargs):
Beispiel #32
0
"""Defines all test wide settings and variables"""
from os import environ

from domaintools import API
from vcr import VCR


def remove_server(response):
    response.get('headers', {}).pop('server', None)
    return response


vcr = VCR(before_record_response=remove_server, filter_query_parameters=['api_key', 'api_username'],
          cassette_library_dir='tests/fixtures/vcr/', path_transformer=VCR.ensure_suffix('.yaml'),
          record_mode='new_episodes')
with vcr.use_cassette('init_user_account'):
    api = API(environ.get('TEST_USER', 'test_user'), environ.get('TEST_KEY', 'test_key'))
Beispiel #33
0
def get_path_transformer(config):
    if "serializer" in config:
        suffix = ".{}".format(config["serializer"])
    else:
        suffix = ".yaml"
    return VCR.ensure_suffix(suffix)
Beispiel #34
0
    session.server_url = 'http://example.com'
    return session


@pytest.fixture()
def session_fixture():
    options = copy.deepcopy(Yagocd.DEFAULT_OPTIONS)
    options['server'] = 'http://local.docker:8153/'
    return Session(
        auth=('admin', '12345'),
        options=options
    )


my_vcr_object = VCR(
    path_transformer=VCR.ensure_suffix('.yaml'),
    cassette_library_dir=os.path.join(tests_dir(), 'fixtures/cassettes'),
)


@pytest.fixture()
def my_vcr():
    return my_vcr_object


CONTAINER_NAME = 'yagocd-server'
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


def pytest_addoption(parser):
    parser.addoption(
Beispiel #35
0
# -*- coding: utf-8 -*-

import bot_mock
from pyfibot.modules import module_urltitle

from utils import check_re
import pytest

from vcr import VCR

my_vcr = VCR(
    path_transformer=VCR.ensure_suffix(".yaml"),
    cassette_library_dir="tests/cassettes/",
    record_mode=pytest.config.getoption("--vcrmode"),
)


@pytest.fixture
def botmock():
    bot = bot_mock.BotMock()
    module_urltitle.init(bot)
    return bot


length_str_regex = u"\d+(h|m|s)(\d+(m))?(\d+s)?"
views_str_regex = u"\d+(\.\d+)?(k|M|Billion|Trillion)?"
age_str_regex = u"(FRESH|(\d+(\.\d+)?(y|d) (ago|from now)))"


@my_vcr.use_cassette
def test_areena_radio(botmock):
Beispiel #36
0
def my_vcr(gocd_docker):
    return VCR(
        path_transformer=VCR.ensure_suffix('.yaml'),
        cassette_library_dir=os.path.join(root_cassette_library_dir, gocd_docker),
    )