0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CDK(Python)のテストコード内で任意のContextをSetして利用する方法

Posted at

PythonでCDKのテストを書いていたのですが、contextの内容を任意の値で設定したいところがありました。

現象

ネットを探したところ set_context() を利用することで任意のcontext値を設定できそうだったので以下のように書いてみたのですが、

def test_set_context():
    test_key = "context_key"
    test_context = {"dummy_key": "dummy_value"}

    app = cdk.App()
    app.node.set_context(test_key, test_context)
    context = app.node.try_get_context(test_key)
    assert context == test_context

例外が発生してしまいました。

raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Cannot set context after children have been added: Tree

対応

App の初期化自に名前付引数の context で渡してあげると設定することができました。

def test_set_context():
    test_key = "context_key"
    test_context = {"dummy_key": "dummy_value"}

    app = cdk.App(context={test_key: test_context})
    context = app.node.try_get_context(test_key)
    assert context == test_context
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?