Giter Site home page Giter Site logo

snowflake-vcrpy's Introduction

Introduction

snowflake-vcrpy is a library that allows you to record and replay HTTP interactions initiated by snowflake-connector-python for testing purposes. It is a pytest plugin built upon VCR.py. Libraries like snowpark-python and snowflake-sqlalchemy depending on the connector for HTTP interactions can also leverage the library.

snowflake-vcrpy provides the following features:

  1. pytest fixtures to enable record and replay HTTP-based tests
  2. pytest options to select the tests run in record-and-replay mode

Installation

snowflake-vcrpy can be installed from source code:

$ git clone [email protected]:Snowflake-Labs/snowflake-vcrpy.git
$ cd snowflake-vcrpy
$ pip install .

Quick Start

Annotate a test with pytest marker to run in record-and-replay mode

# Annotate the test to run in record-and-replay mode
import snowflake.connector
@pytest.mark.snowflake_vcr
def test_method():
    CONNECTION_PARAMETERS = {} # snowflake credentials
    with snowflake.connector.connect(**CONNECTION_PARAMETERS) as conn, conn.cursor() as cursor:
        assert cursor.execute('select 1').fetchall() == [(1,)]

Run with pytest

As a pytest plugin, snowflake-vcrpy by default will identify tests annotated with @pytest.mark.snowflake_vcr and run those tests in record-and-replay mode.

$pytest <test_file.py>

Rationale

snowflake-vcrpy incorporated VCR.py to achieve recording and replaying.

The first time the test is run, a recording file consisting of HTTP requests and responses, will be generated under the directory <your_test_folder>/cassettes with the naming convention of <test_class_name>.<test_method_name>.yaml.

VCR.py will retrieve the serialized requests and responses stored in the cassette file, and if it recognizes any HTTP requests from the original test run, it will intercept them and return the corresponding recorded responses.

To accommodate any changes made to the API of the server being tested or responses, simply remove the existing cassette files and rerun your tests. VCR.py will identify the missing cassette files and automatically record all HTTP interactions.

For advanced topics such as how request matching works or what options VCR.py provides, please refer to the VCP.py documentation. To configure VCR.py within snowflake-vcrpy, please refer to section Optional vcrpy configuration.

pytest options to run tests in record-and-replay mode

Specifying tests

A pytest option is provided to select the tests run in record and replay mode: --snowflake-record-tests-selectio and there are three modes annotated, disable, all:

  • annotated: This is the default mode, pytest will only run the tests annotated with @pytest.mark.snowflake_vcr in record and replay mode.
  • disable: This will disable record and replay for all tests.
  • all This will all tests in record and replay regardless of whether the test is annotated with @pytest.mark.snowflake_vcr.
# run tests which are annotated with `@pytest.mark.snowflake_vcr` in record and replay, this is the default mode
$ pytest <tests>
# run tests which are annotated with `@pytest.mark.snowflake_vcr` in record and replay, with explicitly setting the default mode
$ pytest <tests> --snowflake-record-tests-selection annotated
# disable running record and replay mode for all the tests
$ pytest <tests> --snowflake-record-tests-selection disable
# run all the tests in record and replay regardless of whether the tests are being annotated with `@pytest.mark.snowflake_vcr`
$ pytest <tests> --snowflake-record-tests-selection all

Optional vcrpy configuration

Customized vcrpy config per test case

vcr_config = {
    'path': '<path_to_recording>'
    # for more configs please refer to: https://vcrpy.readthedocs.io/en/latest/configuration.html
}
@pytest.mark.snowflake_vcr(**vcr_config)
def test_method_passing_vcr_config():
    pass

Global pytest fixture

snowflake-vcrpy pytest plugin will read the pytest fixture snowflake_vcr_config to create module-scope VCR instance. If configs are also provided through pytest marker kwargs, then the global fixture configs will be overridden.

@pytest.fixture(scope="module")
def snowflake_vcr_config():
    return {
        # your vcr config dict
    }

snowflake-vcrpy's People

Contributors

sfc-gh-aling avatar sfc-gh-yuwang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

snowflake-vcrpy's Issues

Assumed AWS request URI causes problems.

Hey,

I just found this package and it seems like a very nice one. I decided to test it out since currently a lot of my time goes to waiting for tests to pass. I think this package seems very good.

However, I ran into a problem. The package seems to assume a certain format for the result id from aws requests which, at least for my code, does not hold. I get a IndexError: list index out of range error on line this line code = request.uri.split("/results/")[1].split("/")[0] of the def _process_request_recording(request): function of snowflake_vcrpy_pytest_plugin.py (link to line). I was able to simply comment out that line and the one that depends on it to get everything running (no clue what the implications are).

The request.uristring is https://00000000-0000-0000-0000-000000000000.amazonaws.com/?accelerate

Edit: This seems to have been introduced in the latest commit to the package

Request: a more compatible, robust approach

Thanks for starting this. It's a welcome effort towards making writing tests against snowflake-connector-pythons APIs more feasible.

However, for those of us already using VCR.py, or anyone who'd want to, the current implementation creates as many problems as it solves. The underlying issue, AFAICT, is the choice to vendor VCR.py, instead of simply declaring it as a dependency. Anyone already using VCR.py will now get a second version of it, which introduces needless complexity, and has, in my experience so far, made it very tricky to actually use without breaking things. Hard-coding some config values, and exposing a different configuration API than VCR.py does, or plugins like pytest-recording do, only complicates matters.

Perhaps there's context I'm missing, but as best as I can tell, the root issue is that snowflake-connector-python takes the same approach with respect to requests and urllib3, vendoring them. VCR.py knows how to patch plain urllib3, and the versions that come packaged with botocore and requests, but doesn't know about this new variant. A robust fix for this—and robustness is certainly desirable when it comes to testing tools—would involve extending VCR.py using its public APIs, or opening a PR against it, if those APIs are too limited. (I'm assuming that, for reasons, snowflake-connector-python won't switch to using a standard version of requests or urllib3 anytime soon.)

Again, this is a welcome effort, but its real world utility will greatly limited if it doesn't integrate well with the popular tools on which its based.

Support snowflake.connector.pandas_tools.write_pandas

Use of snowflake.connector.pandas_tools.write_pandas fails with:

  File "./.venv/lib/python3.11/site-packages/snowflakeutils/table.py", line 329, in write_as_dataframe
    res = snowflake.connector.pandas_tools.write_pandas(
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/pandas_tools.py", line 344, in write_pandas
    cursor.execute(upload_sql, _is_internal=True)
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/cursor.py", line 1098, in execute
    sf_file_transfer_agent.execute()
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/file_transfer_agent.py", line 398, in execute
    self._transfer_accelerate_config()
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/file_transfer_agent.py", line 697, in _transfer_accelerate_config
    client = self._create_file_transfer_client(self._file_metadata[0])
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/file_transfer_agent.py", line 676, in _create_file_transfer_client
    return SnowflakeS3RestClient(
           ^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/s3_storage_client.py", line 90, in __init__
    self.transfer_accelerate_config(use_accelerate_endpoint)
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/s3_storage_client.py", line 106, in transfer_accelerate_config
    use_accelerate_endpoint = self._get_bucket_accelerate_config(
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/s3_storage_client.py", line 572, in _get_bucket_accelerate_config
    response = self._send_request_with_authentication_and_retry(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/s3_storage_client.py", line 362, in _send_request_with_authentication_and_retry
    return self._send_request_with_retry(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/storage_client.py", line 287, in _send_request_with_retry
    response = session.request(verb, url, **rest_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/vendored/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/vendored/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/vendored/requests/adapters.py", line 486, in send
    resp = conn.urlopen(
           ^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 715, in urlopen
    httplib_response = self._make_request(
                       ^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 458, in _make_request
    httplib_response = conn.getresponse(buffering=True)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/vcrpy/_vendored/vcrpy/stubs/__init__.py", line 223, in getresponse
    if self.cassette.can_play_response_for(self._vcr_request):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/vcrpy/_vendored/vcrpy/cassette.py", line 269, in can_play_response_for
    request = self._before_record_request(request)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/vcrpy/_vendored/vcrpy/config.py", line 226, in before_record_request
    request = function(request)
              ^^^^^^^^^^^^^^^^^
  File "./.venv/lib/python3.11/site-packages/snowflake/vcrpy/snowflake_vcrpy_pytest_plugin.py", line 41, in _process_request_recording
    code = request.uri.split("/results/")[1].split("/")[0]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.