kandi background
Explore Kits

prefect | The easiest way to automate your data | BPM library

 by   PrefectHQ Python Version: 1.2.0 License: Apache-2.0

 by   PrefectHQ Python Version: 1.2.0 License: Apache-2.0

Download this library from

kandi X-RAY | prefect Summary

prefect is a Python library typically used in Automation, BPM applications. prefect has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub.
From the Latin praefectus, meaning "one who is in charge", a prefect is an official who oversees a domain and makes sure that the rules are followed. Similarly, Prefect is responsible for making sure that workflows execute properly. It also happens to be the name of a roving researcher for that wholly remarkable book, The Hitchhiker's Guide to the Galaxy.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • prefect has a highly active ecosystem.
  • It has 8737 star(s) with 863 fork(s). There are 145 watchers for this library.
  • There were 7 major release(s) in the last 12 months.
  • There are 481 open issues and 1704 have been closed. On average issues are closed in 52 days. There are 14 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of prefect is 1.2.0
prefect Support
Best in #BPM
Average in #BPM
prefect Support
Best in #BPM
Average in #BPM

quality kandi Quality

  • prefect has 0 bugs and 0 code smells.
prefect Quality
Best in #BPM
Average in #BPM
prefect Quality
Best in #BPM
Average in #BPM

securitySecurity

  • prefect has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • prefect code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
prefect Security
Best in #BPM
Average in #BPM
prefect Security
Best in #BPM
Average in #BPM

license License

  • prefect is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
prefect License
Best in #BPM
Average in #BPM
prefect License
Best in #BPM
Average in #BPM

buildReuse

  • prefect releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • It has 76349 lines of code, 6248 functions and 579 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
prefect Reuse
Best in #BPM
Average in #BPM
prefect Reuse
Best in #BPM
Average in #BPM
Top functions reviewed by kandi - BETA

kandi has reviewed prefect and discovered the below as its top functions. This is intended to give you an instant insight into prefect implemented functionality, and help decide if they suit your requirements.

  • Upgrade flow table
    • Replace block_type_name_name with a slug
    • Print an error message
    • Print a message and exit
  • Build a new deployment
    • Return aorion client
    • Create a new Flask application
    • Create a work queue with the given name
  • Returns a dict of cmdclass based on cmdclass
    • Extract the version information
  • Create a deployment from a flow
    • Drop all indexes
      • Set the state of a flow run
        • Update the block document
          • Creates aorption client
            • Set the deployment schedule
              • Create a flow run in the database
                • Set the state of a task run
                  • Load a deployment
                    • Extract version information from VCS
                      • Create a container
                        • Read block schemas
                          • Login to Google
                            • Start a work queue
                              • Run a deployed flow
                                • Start a task run
                                  • Adds a type field to the model
                                    • Create the versioneer config file

                                      Get all kandi verified functions for this library.

                                      Get all kandi verified functions for this library.

                                      prefect Key Features

                                      The easiest way to automate your data

                                      prefect Examples and Code Snippets

                                      See all related Code Snippets

                                      Welcome to Workflows

                                      copy iconCopydownload iconDownload
                                      from prefect import task, Flow, Parameter
                                      
                                      
                                      @task(log_stdout=True)
                                      def say_hello(name):
                                          print("Hello, {}!".format(name))
                                      
                                      
                                      with Flow("My First Flow") as flow:
                                          name = Parameter('name')
                                          say_hello(name)
                                      
                                      
                                      flow.run(name='world') # "Hello, world!"
                                      flow.run(name='Marvin') # "Hello, Marvin!"
                                      

                                      UI and Server

                                      copy iconCopydownload iconDownload
                                      $ prefect backend cloud
                                      

                                      Latest Release

                                      copy iconCopydownload iconDownload
                                      pip install prefect
                                      

                                      Bleeding Edge

                                      copy iconCopydownload iconDownload
                                      git clone https://github.com/PrefectHQ/prefect.git
                                      pip install ./prefect
                                      

                                      How to mock functions with same name, when called twice?

                                      copy iconCopydownload iconDownload
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      
                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      
                                      python -m unittest code_test.py
                                      
                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      

                                      Queryset takes too long to populate data

                                      copy iconCopydownload iconDownload
                                      self.fields['borrower_id'].Student.objects.filter(
                                          school=school
                                      ).select_related('klass', 'stream')

                                      Writing input to c executable manually trigger exploit, but python input does not

                                      copy iconCopydownload iconDownload
                                      ./form $(python -c "print('%x'*3)")
                                      
                                      /form &
                                      (python -c "print('%x'*3)")
                                      
                                      ./form $(python -c "print('%x'*3)")
                                      
                                      /form &
                                      (python -c "print('%x'*3)")
                                      

                                      Using dropdown filter to dynamic update Highchart

                                      copy iconCopydownload iconDownload
                                       <select id="select_media" onchange="update()" >
                                      
                                      function update() {
                                         // getting drop down list value
                                         var mediaselect = document.getElementById("select_media").value
                                         mediaselect_str = String(mediaselect)
                                      
                                         const parsedData = []
                                         data.forEach(obj => {
                                             if (obj.Media == mediaselect_str) {
                                             parsedData.push({
                                                 x: parseInt(obj.Row),
                                                 y: parseInt(obj.Column),
                                                 label: [obj.Data, obj.Media, obj.Code]
                                             })
                                             }
                                         });
                                      
                                         var chart = Highcharts.chart('tray_container', {
                                             chart: {
                                                 type: 'heatmap',
                                                 width: 500,
                                                 height: 500,            
                                             
                                             },
                                             title: {
                                                 text: null
                                             },
                                             plotOptions: {
                                                 heatmap: {
                                                     borderColor: "black",
                                                     paddingRight: 100
                                                 },
                                             },
                                             series: [{
                                                 name: null,
                                                 borderWidth: 1,
                                                 data: parsedData,
                                                 dataLabels: {
                                                     inside: true,//Show 
                                                     enabled: true,
                                                     useHTML: true,
                                                     opacity: 1,
                                                     verticalAlign:'middle',
                                                     align: 'center',
                                                     style: {
                                                         textShadow: 'none',
                                                         HcTextStroke: null,
                                                         display: 'block'
                                                 },
                                                     formatter: function() {
                                                     const label = this.point.label;
                                                     return `${label[1]} <br/> ${label[2]} <br/> ${label[0]}`
                                                     }
                                                 },
                                             }]
                                         });
                                        }
                                      
                                       <select id="select_media" onchange="update()" >
                                      
                                      function update() {
                                         // getting drop down list value
                                         var mediaselect = document.getElementById("select_media").value
                                         mediaselect_str = String(mediaselect)
                                      
                                         const parsedData = []
                                         data.forEach(obj => {
                                             if (obj.Media == mediaselect_str) {
                                             parsedData.push({
                                                 x: parseInt(obj.Row),
                                                 y: parseInt(obj.Column),
                                                 label: [obj.Data, obj.Media, obj.Code]
                                             })
                                             }
                                         });
                                      
                                         var chart = Highcharts.chart('tray_container', {
                                             chart: {
                                                 type: 'heatmap',
                                                 width: 500,
                                                 height: 500,            
                                             
                                             },
                                             title: {
                                                 text: null
                                             },
                                             plotOptions: {
                                                 heatmap: {
                                                     borderColor: "black",
                                                     paddingRight: 100
                                                 },
                                             },
                                             series: [{
                                                 name: null,
                                                 borderWidth: 1,
                                                 data: parsedData,
                                                 dataLabels: {
                                                     inside: true,//Show 
                                                     enabled: true,
                                                     useHTML: true,
                                                     opacity: 1,
                                                     verticalAlign:'middle',
                                                     align: 'center',
                                                     style: {
                                                         textShadow: 'none',
                                                         HcTextStroke: null,
                                                         display: 'block'
                                                 },
                                                     formatter: function() {
                                                     const label = this.point.label;
                                                     return `${label[1]} <br/> ${label[2]} <br/> ${label[0]}`
                                                     }
                                                 },
                                             }]
                                         });
                                        }
                                      
                                      const data = {
                                        data1: [
                                          [0, 0, 10],
                                          [0, 1, 19],
                                          [0, 2, 8],
                                          [0, 3, 24],
                                          [0, 4, 67],
                                          [1, 0, 92],
                                        ],
                                      
                                        data2: [
                                          [1, 1, 58],
                                          [1, 2, 78],
                                          [1, 3, 117],
                                          [1, 4, 48],
                                          [2, 0, 35],
                                          [2, 1, 15],
                                        ],
                                      
                                        data3: [
                                          [2, 2, 123],
                                          [2, 3, 64],
                                          [2, 4, 52],
                                          [3, 0, 72],
                                          [3, 1, 132],
                                          [3, 2, 114],
                                        ]
                                      }
                                      
                                      
                                      const chart = Highcharts.chart('container', {
                                        chart: {
                                          type: 'heatmap'
                                        },
                                        series: [{
                                          data: data.data1
                                        }]
                                      });
                                      
                                      var select = document.getElementById('select');
                                      
                                      select.addEventListener('change', function() {
                                        chart.series[0].update({
                                          data: data[this.value]
                                        });
                                      });
                                      

                                      How to deploy a Kubernetes Job at AKS with Prefect

                                      copy iconCopydownload iconDownload
                                      prefect agent kubernetes install --rbac --key YOUR_API_KEY --label YOUR_LABEL > agent.yaml
                                      
                                      kubectl apply -f agent.yaml # optionally set: -n yournamespace 
                                      
                                      import prefect
                                      from prefect import task, Flow
                                      from prefect.run_configs import KubernetesRun
                                      
                                      
                                      @task
                                      def hello_task():
                                          logger = prefect.context.get("logger")
                                          logger.info("Hello world!")
                                      
                                      
                                      with Flow("hello-flow", run_config=KubernetesRun(labels=["YOUR_LABEL"])) as flow:
                                          hello_task()
                                      
                                      if __name__ == "__main__":
                                          flow.register("YOUR_PROJECT_NAME")
                                      
                                      prefect register --project YOUR_PROJECT_NAME -p path/to/flow.py
                                      
                                      prefect run --name "hello-flow" --project YOUR_PROJECT_NAME --watch
                                      
                                      prefect agent kubernetes install --rbac --key YOUR_API_KEY --label YOUR_LABEL > agent.yaml
                                      
                                      kubectl apply -f agent.yaml # optionally set: -n yournamespace 
                                      
                                      import prefect
                                      from prefect import task, Flow
                                      from prefect.run_configs import KubernetesRun
                                      
                                      
                                      @task
                                      def hello_task():
                                          logger = prefect.context.get("logger")
                                          logger.info("Hello world!")
                                      
                                      
                                      with Flow("hello-flow", run_config=KubernetesRun(labels=["YOUR_LABEL"])) as flow:
                                          hello_task()
                                      
                                      if __name__ == "__main__":
                                          flow.register("YOUR_PROJECT_NAME")
                                      
                                      prefect register --project YOUR_PROJECT_NAME -p path/to/flow.py
                                      
                                      prefect run --name "hello-flow" --project YOUR_PROJECT_NAME --watch
                                      
                                      prefect agent kubernetes install --rbac --key YOUR_API_KEY --label YOUR_LABEL > agent.yaml
                                      
                                      kubectl apply -f agent.yaml # optionally set: -n yournamespace 
                                      
                                      import prefect
                                      from prefect import task, Flow
                                      from prefect.run_configs import KubernetesRun
                                      
                                      
                                      @task
                                      def hello_task():
                                          logger = prefect.context.get("logger")
                                          logger.info("Hello world!")
                                      
                                      
                                      with Flow("hello-flow", run_config=KubernetesRun(labels=["YOUR_LABEL"])) as flow:
                                          hello_task()
                                      
                                      if __name__ == "__main__":
                                          flow.register("YOUR_PROJECT_NAME")
                                      
                                      prefect register --project YOUR_PROJECT_NAME -p path/to/flow.py
                                      
                                      prefect run --name "hello-flow" --project YOUR_PROJECT_NAME --watch
                                      
                                      prefect agent kubernetes install --rbac --key YOUR_API_KEY --label YOUR_LABEL > agent.yaml
                                      
                                      kubectl apply -f agent.yaml # optionally set: -n yournamespace 
                                      
                                      import prefect
                                      from prefect import task, Flow
                                      from prefect.run_configs import KubernetesRun
                                      
                                      
                                      @task
                                      def hello_task():
                                          logger = prefect.context.get("logger")
                                          logger.info("Hello world!")
                                      
                                      
                                      with Flow("hello-flow", run_config=KubernetesRun(labels=["YOUR_LABEL"])) as flow:
                                          hello_task()
                                      
                                      if __name__ == "__main__":
                                          flow.register("YOUR_PROJECT_NAME")
                                      
                                      prefect register --project YOUR_PROJECT_NAME -p path/to/flow.py
                                      
                                      prefect run --name "hello-flow" --project YOUR_PROJECT_NAME --watch
                                      
                                      prefect agent kubernetes install --rbac --key YOUR_API_KEY --label YOUR_LABEL > agent.yaml
                                      
                                      kubectl apply -f agent.yaml # optionally set: -n yournamespace 
                                      
                                      import prefect
                                      from prefect import task, Flow
                                      from prefect.run_configs import KubernetesRun
                                      
                                      
                                      @task
                                      def hello_task():
                                          logger = prefect.context.get("logger")
                                          logger.info("Hello world!")
                                      
                                      
                                      with Flow("hello-flow", run_config=KubernetesRun(labels=["YOUR_LABEL"])) as flow:
                                          hello_task()
                                      
                                      if __name__ == "__main__":
                                          flow.register("YOUR_PROJECT_NAME")
                                      
                                      prefect register --project YOUR_PROJECT_NAME -p path/to/flow.py
                                      
                                      prefect run --name "hello-flow" --project YOUR_PROJECT_NAME --watch
                                      

                                      prefect.io kubernetes agent and task execution

                                      copy iconCopydownload iconDownload
                                              env:
                                              - name: PREFECT__CLOUD__AGENT__AUTH_TOKEN
                                                value: ''
                                              - name: PREFECT__CLOUD__API
                                                value: "http://some_ip:4200/graphql" # paste your GraphQL Server endpoint here
                                              - name: PREFECT__BACKEND
                                                value: server
                                      
                                      from prefect import Flow, task, case
                                      from prefect.tasks.prefect import create_flow_run, wait_for_flow_run
                                      from prefect.run_configs import DockerRun, KubernetesRun
                                      
                                      
                                      @task
                                      def check_the_infrastructure():
                                          return "kubernetes"
                                      
                                      
                                      with Flow("parent_flow") as flow:
                                          infra = check_the_infrastructure()
                                          with case(infra, "kubernetes"):
                                              child_flow_run_id = create_flow_run(
                                                  flow_name="child_flow_name", run_config=KubernetesRun()
                                              )
                                              k8_child_flowrunview = wait_for_flow_run(
                                                  child_flow_run_id, raise_final_state=True, stream_logs=True
                                              )
                                          with case(infra, "docker"):
                                              child_flow_run_id = create_flow_run(
                                                  flow_name="child_flow_name", run_config=DockerRun()
                                              )
                                              docker_child_flowrunview = wait_for_flow_run(
                                                  child_flow_run_id, raise_final_state=True, stream_logs=True
                                              )
                                      
                                              env:
                                              - name: PREFECT__CLOUD__AGENT__AUTH_TOKEN
                                                value: ''
                                              - name: PREFECT__CLOUD__API
                                                value: "http://some_ip:4200/graphql" # paste your GraphQL Server endpoint here
                                              - name: PREFECT__BACKEND
                                                value: server
                                      
                                      from prefect import Flow, task, case
                                      from prefect.tasks.prefect import create_flow_run, wait_for_flow_run
                                      from prefect.run_configs import DockerRun, KubernetesRun
                                      
                                      
                                      @task
                                      def check_the_infrastructure():
                                          return "kubernetes"
                                      
                                      
                                      with Flow("parent_flow") as flow:
                                          infra = check_the_infrastructure()
                                          with case(infra, "kubernetes"):
                                              child_flow_run_id = create_flow_run(
                                                  flow_name="child_flow_name", run_config=KubernetesRun()
                                              )
                                              k8_child_flowrunview = wait_for_flow_run(
                                                  child_flow_run_id, raise_final_state=True, stream_logs=True
                                              )
                                          with case(infra, "docker"):
                                              child_flow_run_id = create_flow_run(
                                                  flow_name="child_flow_name", run_config=DockerRun()
                                              )
                                              docker_child_flowrunview = wait_for_flow_run(
                                                  child_flow_run_id, raise_final_state=True, stream_logs=True
                                              )
                                      

                                      Supervisor kills Prefect agent with SIGTERM unexpectedly

                                      copy iconCopydownload iconDownload
                                      supervisorctl status
                                      
                                      [program:prefect-agent]
                                      command=prefect agent local start -l raspberry -k YOUR_API_KEY --no-hostname-label
                                      directory=/home/pi/.local/bin/prefect
                                      user=pi
                                      environment=HOME="/home/pi/.local/bin/prefect",USER="pi"
                                      
                                      supervisorctl status
                                      
                                      [program:prefect-agent]
                                      command=prefect agent local start -l raspberry -k YOUR_API_KEY --no-hostname-label
                                      directory=/home/pi/.local/bin/prefect
                                      user=pi
                                      environment=HOME="/home/pi/.local/bin/prefect",USER="pi"
                                      

                                      How to create a subrange of a BTreeSet&lt;(String, String, String)&gt;? How to turn a tuple of bounds into a bound of a tuple?

                                      copy iconCopydownload iconDownload
                                      all entities;
                                      all entities with an ID in range x..y;
                                      all fields of entity 1;
                                      the current value of entity 1's "user/age" field).
                                      
                                      use std::collections::BTreeSet;
                                      use std::ops::Bound;
                                      
                                      type Entity = String;
                                      type Attribute = String;
                                      type Value = String;
                                      type EAV = (Entity, Attribute, Value);
                                      type EAVSet = BTreeSet<EAV>;
                                      
                                      pub fn example_db() -> EAVSet {
                                          let mut example: EAVSet = BTreeSet::new();
                                          insert_strtup(&mut example, ("1", "type", "user"));
                                          insert_strtup(&mut example, ("1", "user/name", "Arthur Dent"));
                                          insert_strtup(&mut example, ("1", "user/age", "33"));
                                      
                                          insert_strtup(&mut example, ("2", "type", "user"));
                                          insert_strtup(&mut example, ("2", "user/name", "Ford Prefect"));
                                          insert_strtup(&mut example, ("2", "user/age", "42"));
                                      
                                          insert_strtup(&mut example, ("11", "type", "user"));
                                          insert_strtup(&mut example, ("11", "user/name", "Arthur Dent"));
                                          insert_strtup(&mut example, ("11", "user/age", "33"));
                                      
                                          insert_strtup(&mut example, ("12", "type", "user"));
                                          insert_strtup(&mut example, ("12", "user/name", "Ford Prefect"));
                                          insert_strtup(&mut example, ("12", "user/age", "42"));
                                          return example;
                                      }
                                      
                                      fn insert_strtup(db: &mut EAVSet, val: (&str, &str, &str)) -> () {
                                          db.insert((val.0.to_string(), val.1.to_string(), val.2.to_string()));
                                      }
                                      
                                      static MAX_STRING: &str = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
                                      
                                      pub fn main() {
                                          let db = example_db();
                                      
                                          // How to customize this?
                                          let range: (Bound<EAV>, Bound<EAV>) = (Bound::Unbounded, Bound::Unbounded);
                                      
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tall entities with an ID in range \"11\"..=\"12\":");
                                      
                                          let range = (
                                              Bound::Included(("11".to_string(), "".to_string(), "".to_string())),
                                              Bound::Excluded(("120".to_string(), "".to_string(), "".to_string())),
                                          );
                                      
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tall fields of entity 1:");
                                      
                                          let range = (
                                              Bound::Included(("1".to_string(), "".to_string(), "".to_string())),
                                              Bound::Excluded(("10".to_string(), "".to_string(), "".to_string())),
                                          );
                                          
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tthe current value of entity 1's \"user/age\" field:");
                                      
                                          let range = (
                                              Bound::Included(("1".to_string(), "user/age".to_string(), "".to_string())),
                                              Bound::Excluded(("1".to_string(), "user/age".to_string(), MAX_STRING.to_string())),
                                          );
                                          
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      }
                                      
                                      all entities;
                                      all entities with an ID in range x..y;
                                      all fields of entity 1;
                                      the current value of entity 1's "user/age" field).
                                      
                                      use std::collections::BTreeSet;
                                      use std::ops::Bound;
                                      
                                      type Entity = String;
                                      type Attribute = String;
                                      type Value = String;
                                      type EAV = (Entity, Attribute, Value);
                                      type EAVSet = BTreeSet<EAV>;
                                      
                                      pub fn example_db() -> EAVSet {
                                          let mut example: EAVSet = BTreeSet::new();
                                          insert_strtup(&mut example, ("1", "type", "user"));
                                          insert_strtup(&mut example, ("1", "user/name", "Arthur Dent"));
                                          insert_strtup(&mut example, ("1", "user/age", "33"));
                                      
                                          insert_strtup(&mut example, ("2", "type", "user"));
                                          insert_strtup(&mut example, ("2", "user/name", "Ford Prefect"));
                                          insert_strtup(&mut example, ("2", "user/age", "42"));
                                      
                                          insert_strtup(&mut example, ("11", "type", "user"));
                                          insert_strtup(&mut example, ("11", "user/name", "Arthur Dent"));
                                          insert_strtup(&mut example, ("11", "user/age", "33"));
                                      
                                          insert_strtup(&mut example, ("12", "type", "user"));
                                          insert_strtup(&mut example, ("12", "user/name", "Ford Prefect"));
                                          insert_strtup(&mut example, ("12", "user/age", "42"));
                                          return example;
                                      }
                                      
                                      fn insert_strtup(db: &mut EAVSet, val: (&str, &str, &str)) -> () {
                                          db.insert((val.0.to_string(), val.1.to_string(), val.2.to_string()));
                                      }
                                      
                                      static MAX_STRING: &str = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
                                      
                                      pub fn main() {
                                          let db = example_db();
                                      
                                          // How to customize this?
                                          let range: (Bound<EAV>, Bound<EAV>) = (Bound::Unbounded, Bound::Unbounded);
                                      
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tall entities with an ID in range \"11\"..=\"12\":");
                                      
                                          let range = (
                                              Bound::Included(("11".to_string(), "".to_string(), "".to_string())),
                                              Bound::Excluded(("120".to_string(), "".to_string(), "".to_string())),
                                          );
                                      
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tall fields of entity 1:");
                                      
                                          let range = (
                                              Bound::Included(("1".to_string(), "".to_string(), "".to_string())),
                                              Bound::Excluded(("10".to_string(), "".to_string(), "".to_string())),
                                          );
                                          
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      
                                          println!("\tthe current value of entity 1's \"user/age\" field:");
                                      
                                          let range = (
                                              Bound::Included(("1".to_string(), "user/age".to_string(), "".to_string())),
                                              Bound::Excluded(("1".to_string(), "user/age".to_string(), MAX_STRING.to_string())),
                                          );
                                          
                                          for elem in db.range(range) {
                                              println!("{:?}", elem);
                                          }
                                      }
                                      
                                      use std::borrow::Borrow;
                                      use std::cmp::Ordering;
                                      
                                      #[repr(transparent)]
                                      pub struct StringWithMinMaxSentinel(String);
                                      
                                      // must be static, not const, to ensure a constant memory address
                                      pub static STRING_MIN_SENTINEL: StringWithMinMaxSentinel = StringWithMinMaxSentinel(String::new());
                                      pub static STRING_MAX_SENTINEL: StringWithMinMaxSentinel = StringWithMinMaxSentinel(String::new());
                                      
                                      impl Borrow<StringWithMinMaxSentinel> for String {
                                          fn borrow(self: &String) -> &StringWithMinMaxSentinel {
                                              unsafe { &*(self as *const String as *const StringWithMinMaxSentinel) }
                                          }
                                      }
                                      
                                      impl PartialEq for StringWithMinMaxSentinel {
                                          fn eq(&self, other: &Self) -> bool {
                                              std::ptr::eq(self, other) || (!std::ptr::eq(self, &STRING_MIN_SENTINEL) && !std::ptr::eq(other, &STRING_MAX_SENTINEL) && !std::ptr::eq(other, &STRING_MIN_SENTINEL) && !std::ptr::eq(self, &STRING_MAX_SENTINEL) && self.0.eq(&other.0))
                                          }
                                      }
                                      
                                      impl Eq for StringWithMinMaxSentinel {}
                                      
                                      impl PartialOrd for StringWithMinMaxSentinel {
                                          fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                                              Some(self.cmp(other))
                                          }
                                      }
                                      
                                      impl Ord for StringWithMinMaxSentinel {
                                          fn cmp(&self, other: &Self) -> Ordering {
                                              if std::ptr::eq(self, other) {
                                                  Ordering::Equal
                                              } else if std::ptr::eq(self, &STRING_MIN_SENTINEL) || std::ptr::eq(other, &STRING_MAX_SENTINEL) {
                                                  Ordering::Less
                                              } else if std::ptr::eq(self, &STRING_MAX_SENTINEL) || std::ptr::eq(other, &STRING_MIN_SENTINEL) {
                                                  Ordering::Greater
                                              } else {
                                                  self.0.cmp(&other.0)
                                              }
                                          }
                                      }
                                      

                                      Invalid JSON response in datatables server proccessing

                                      copy iconCopydownload iconDownload
                                      if($stmt->rowCount() > 0){
                                          var_dump($row[$column]);exit;
                                          //return $row[$column];
                                      }
                                      
                                      $table = '(SELECT u.*, r.role_name FROM users u INNER JOIN roles r ON u.role_id = r.id) tbl';
                                      

                                      Prefect Task Scheduling

                                      copy iconCopydownload iconDownload
                                      from prefect import task, Flow, Parameter
                                      
                                      
                                      @task
                                      def get_data(board):
                                          pass
                                      
                                      
                                      @task
                                      def check_db(url):
                                          pass
                                      
                                      
                                      @task
                                      def upload_raw(url, board):
                                          pass
                                      
                                      
                                      @task
                                      def remove_duplicates(board):
                                          pass
                                      
                                      
                                      with Flow(name="4chan_extract") as flow:
                                          board_param = Parameter(name="board_name", required=True, default="pol")
                                          data = get_data(board=board_param)
                                          check = check_db(
                                              url="postgresql://postgres:user@localhost:5434/postgres", upstream_tasks=[data]
                                          )
                                          upload = upload_raw(
                                              url="postgresql://postgres:user@localhost:5434/postgres",
                                              board=board_param,
                                              upstream_tasks=[check],
                                          )
                                          remove_duplicates(board=board_param, upstream_tasks=[upload])
                                      
                                      if __name__ == "__main__":
                                          flow.visualize()
                                      

                                      See all related Code Snippets

                                      Community Discussions

                                      Trending Discussions on prefect
                                      • How to mock functions with same name, when called twice?
                                      • Queryset takes too long to populate data
                                      • Writing input to c executable manually trigger exploit, but python input does not
                                      • Using dropdown filter to dynamic update Highchart
                                      • How to deploy a Kubernetes Job at AKS with Prefect
                                      • Delete flow definition in prefect orion
                                      • prefect.io kubernetes agent and task execution
                                      • Prefect Local Agent Troubleshooting
                                      • Supervisor kills Prefect agent with SIGTERM unexpectedly
                                      • How to solve this issue Execution failed for task ':app:compileFlutterBuildDebug'
                                      Trending Discussions on prefect

                                      QUESTION

                                      How to mock functions with same name, when called twice?

                                      Asked 2022-Mar-26 at 07:48

                                      How do I mock a function which has been called twice in the same file, with different parameters? Here is my code snippet:

                                      code_file.py

                                      from prefect import Client
                                      client = Client(
                                          api_server = <ip of server>
                                      )
                                      def run_flow(name1, name2):
                                           # some graphql queries, not shown here
                                           value1 = client.graphql(graphql_value1, variables={'name': name1})
                                           print("First client call return value:- ", value1)
                                           value2 = client.graphql(graphql_value2, variables={'name': name2, 'id': value1['data'][0]['id']})
                                           print("Second client call return value:- ", value2)
                                      
                                           run_id = client.create_flow(id = value2['data'][0]['id'])
                                              return run_id
                                      

                                      code_test.py

                                      # I want to mock these client calls.
                                      # However when I am mocking, only the first client.graphql function is being mocked. 
                                      # How do I mock the other client.graphql and the client.create_flow function?
                                      
                                      import unittest
                                      import pytest
                                      from pytest_mock import mocker
                                      from unittest.mock import Mock
                                      from fastapi.testclient import TestClient
                                      from app.main import app
                                      
                                      client = TestClient(app)
                                      
                                      class test_flow(unittest.TestCase):
                                       @patch("code_file.client.graphql", side_effect=["test1s", "test2s"])
                                       @patch("code_file.client.create_flow", return_value="test_id")
                                       def test_flow(self, s1):
                                         # Below post call invokes run_flow function
                                         response = client.post("/name1/name2")
                                         assert run_flow("name1", "name2") == "test_id"
                                      

                                      First mock call to graphql is succeeding. The second graphql call is not getting mocked. It is trying to contact the actual server and receiving 404. How can I mock both graphql client calls?

                                      ANSWER

                                      Answered 2022-Mar-26 at 07:48

                                      I tried to reproduce your codes, but for me client.graphql got mocked perfectly.

                                      Here are my codes.

                                      Folder structure

                                      ├── code_file.py
                                      ├── code_test.py
                                      └── prefect.py
                                      
                                      # prefect.py
                                      class Client:
                                          def __init__(self, *arg, **kwargs):
                                              ...
                                      
                                          def graphql(self, *args, **kwargs):
                                              print(f"graphql got called with args: {args}, kwargs: {kwargs}")
                                      
                                          def create_flow(self, *args, **kwargs):
                                              print(f"create_flow got called with args: {args}, kwargs: {kwargs}")
                                      
                                      
                                      # code_file.py
                                      from prefect import Client
                                      
                                      graphql_value1 = "graphql_value1"
                                      graphql_value2 = "graphql_value2"
                                      
                                      client = Client(api_server="http://example.com")
                                      
                                      
                                      def run_flow(name1, name2):
                                          # some graphql queries, not shown here
                                          value1 = client.graphql(graphql_value1, variables={"name": name1})
                                          print("First client call return value:- ", value1)
                                          value2 = client.graphql(graphql_value2, variables={"name": name2, "id": value1["data"][0]["id"]})
                                          print("Second client call return value:- ", value2)
                                      
                                          run_id = client.create_flow(id=value2["data"][0]["id"])
                                          return run_id
                                      
                                      # code_test.py
                                      import unittest
                                      from unittest.mock import patch, MagicMock, call
                                      from code_file import run_flow
                                      
                                      
                                      class TestFlow(unittest.TestCase):
                                          @patch("code_file.client.graphql")
                                          @patch("code_file.client.create_flow")
                                          def test_flow(self, create_flow: MagicMock, graphql: MagicMock) -> None:
                                              first_graphql_return_value = {"data": [{"id": 1}]}
                                              second_graphl_return_value = {"data": [{"id": 2}]}
                                              graphql.side_effect = [
                                                  first_graphql_return_value,
                                                  second_graphl_return_value,
                                              ]
                                              create_flow.return_value = "test_id"
                                      
                                              self.assertEqual(run_flow("name1", "name2"), "test_id")
                                      
                                              create_flow.assert_called_once_with(id=2)
                                              graphql.assert_has_calls(
                                                  [
                                                      call("graphql_value1", variables={"name": "name1"}),
                                                      call("graphql_value2", variables={"name": "name2", "id": 1})
                                                  ]
                                              )
                                      
                                      

                                      Running unittest by using the command

                                      python -m unittest code_test.py
                                      

                                      produces the following output

                                      First client call return value:-  {'data': [{'id': 1}]}
                                      Second client call return value:-  {'data': [{'id': 2}]}
                                      .
                                      ----------------------------------------------------------------------
                                      Ran 1 test in 0.001s
                                      

                                      You'll see that the prints in prefect.Client methods do not get printed.

                                      Original answer Explanation

                                      From python official documentation

                                      If side_effect is an iterable then each call to the mock will return the next value from the iterable.

                                      When you set side_effect argument with an iterable, the mock will return next value from the iterable. More detail can be found here

                                      Solution
                                      def test_flow(mocker):
                                          # Some lines of code, not shown here
                                          m = mocker.patch("code_file.client.graphql", side_effect=["value1", "value2"])
                                          ...
                                      

                                      Source https://stackoverflow.com/questions/71610090

                                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                      Vulnerabilities

                                      No vulnerabilities reported

                                      Install prefect

                                      You can download it from GitHub.
                                      You can use prefect like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

                                      Support

                                      Prefect's documentation -- including concepts, tutorials, and a full API reference -- is always available at docs.prefect.io. Instructions for contributing to documentation can be found in the development guide.

                                      DOWNLOAD this Library from

                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                      over 430 million Knowledge Items
                                      Find more libraries
                                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                      Explore Kits

                                      Save this library and start creating your kit

                                      Explore Related Topics

                                      Share this Page

                                      share link
                                      Reuse Pre-built Kits with prefect
                                      Consider Popular BPM Libraries
                                      Try Top Libraries by PrefectHQ
                                      Compare BPM Libraries with Highest Support
                                      Compare BPM Libraries with Highest Quality
                                      Compare BPM Libraries with Highest Security
                                      Compare BPM Libraries with Permissive License
                                      Compare BPM Libraries with Highest Reuse
                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                      over 430 million Knowledge Items
                                      Find more libraries
                                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                      Explore Kits

                                      Save this library and start creating your kit

                                      • © 2022 Open Weaver Inc.