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

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement