henriquesati

henriquesati

How to change context variables based on tags provided by test

I want to test a endpoint that makes external api calls. What I want to do is to only do this external api call once (generate a payload) and only generate new ones when the tag ;value is provided. Here is my tring but on each test it generates a new payload anyway

defmodule TestesPayTest.BusinessRules do
  use ExUnit.Case, async: true
  use Plug.Test
  require Logger
  @create_qr_url "https://sandbox.asaas.com/api/v3/pix/qrCodes/static"
  @pix_key "ab09d852-14bd-43ac-91eb-d38b717e6aea"
 

  setup_all do
    access_token = System.get_env("ACCESS_TOKEN")
    base_fee = 0.0765
    basic_ref_fee = 0.0165
  
    payload =
    case create_payload(100) do
      {:ok, payload} -> payload
      {:error, _reason} -> nil
    end

    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
    Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})
  
    {:ok, %{access_token: access_token, base_fee: base_fee, basic_ref_fee: basic_ref_fee}}
  end

  setup context do
    value = context[:value]
    if value do
      new_payload = 
      case create_payload(value) do
        {:ok, new_payload} ->
          Map.put(context, :payload, new_payload)

        {:error, reason} ->
          Logger.error("Falha ao criar novo payload: #{inspect(reason)}")
          nil
      end
    end

  end

tests

describe "chain invalida" do
    @tag value: 630

    test "POST /api/create_contract", %{payload: payload} do
      Logger.debug("deve ser padrao #{inspect(payload)}")
          body = Jason.encode!(%{
       "chain" => "qlqr",
       "coin" => "ETH",
       "payload" => payload
     })
        conn = conn(:post, "/api/create_contract", body)
    |> put_req_header("content-type", "application/json")
    |> TestesPay.MyRouter.call(body)
    IO.inspect(conn.resp_body)
    expected_error = %{
      "field" => "chain",
      "msg" => "rede invalida"
    }
    assert conn.status == 400
    assert Jason.decode!(conn.resp_body) == expected_error
  end
end


describe "coin invalida" do
  test "POST /api/create_contract", %{payload: payload} do
    Logger.debug("deve ser padrao #{inspect(payload)}")
        body = Jason.encode!(%{
     "chain" => "eth",
     "coin" => "xereb",
     "payload" => payload
   })
      conn = conn(:post, "/api/create_contract", body)
  |> put_req_header("content-type", "application/json")
  |> TestesPay.MyRouter.call(body)
  IO.inspect(conn.resp_body)
  expected_error = %{
    "field" => "coin",
    "msg" => "moeda invalida"
  }

  assert conn.status == 400
  assert Jason.decode!(conn.resp_body) == expected_error
end
end

Marked As Solved

henriquesati

henriquesati


  setup_all do
    access_token = System.get_env("ACCESS_TOKEN")
    base_fee = 0.0765
    basic_ref_fee = 0.0165
    payload = 
    case create_payload(100) do
      {:ok, payload} -> payload
      {:error, _reason} -> :nil
    end

    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
    Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})
  
    {:ok, %{access_token: access_token, payload: payload, base_fee: base_fee, basic_ref_fee: basic_ref_fee}}
  end
setup context do
    value = Map.get(context, :value, nil) # Obtendo a variável 'value' da tag
    value_info = Map.get(context, :value_info, "nao provido")
    Logger.debug("value_info #{inspect(value_info)}")
    Logger.debug("value #{inspect(value)}")
    
    if is_nil(value) do
      {:ok, valuetag: value}
    else
      case create_payload(value) do
        {:ok, payload} -> {:ok, valuetag: value, payload: payload}
        {:error, _reason} -> {:ok, valuetag: value}
      end
    end
  end

 describe "valor contrato com basic_ref_fee" do
    @tag value: 130
    @tag value_info: "sem value"
    test "POST /api/create_contract", %{payload: payload, base_fee: base_fee, basic_ref_fee: basic_ref_fee} do
      Logger.debug("padrao #{inspect(payload)}")
          body = Jason.encode!(%{
        "chain" => "eth",
        "coin" => "eth",
        "payload" => payload,
        "ref" => "refbasicfee"
      })
        conn = conn(:post, "/api/create_contract", body)
      |> put_req_header("content-type", "application/json")
      |> TestesPay.MyRouter.call(body)

      response = Jason.decode!(conn.resp_body)

      mock = get_mock_contract(payload)
      mockval = mock["transaction_value"]
      mockcharged = mock["transaction_charged"]
      mockref_fee = ["ref_fee"]

      assert conn.status == 200
     
    end
  end

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54921 245
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49084 226
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement