From 58c5152d1fb5e84ee811beb72e63b74e415818bf Mon Sep 17 00:00:00 2001 From: Ivan Ivanov Date: Tue, 26 May 2020 14:56:36 +0300 Subject: [PATCH] Rework datetimes handlings --- lib/sanbase/auth/user.ex | 46 ++++++-- lib/sanbase/clickhouse/erc20_transfers.ex | 2 +- lib/sanbase/clickhouse/eth_transfers.ex | 2 +- lib/sanbase/clickhouse/github/github.ex | 2 +- lib/sanbase/comments/comment.ex | 2 + lib/sanbase/comments/entity_comment.ex | 4 +- lib/sanbase/comments/notification.ex | 4 +- lib/sanbase/insight/post.ex | 2 +- lib/sanbase/model/project/roi.ex | 8 +- lib/sanbase/timeline/cursor.ex | 4 +- lib/sanbase/timeline/timeline_event.ex | 4 +- lib/sanbase/utils/datetime/utils.ex | 8 ++ .../graphql/middlewares/access_control.ex | 1 - .../graphql/schema/custom_types/datetime.ex | 4 +- test/sanbase/auth/user_test.exs | 8 +- .../sanbase/clickhouse/api_call_data_test.exs | 1 - test/sanbase/clickhouse/gas_used_test.exs | 1 - .../erc20_assets_held_by_address_test.exs | 1 - .../eth_assets_held_by_address_test.exs | 1 - .../miners_balance_test.exs | 4 +- .../metric/clickhouse_metric_helper_test.exs | 2 - .../mining_pools_distribution_test.exs | 4 +- test/sanbase/clickhouse/top_holders_test.exs | 4 +- test/sanbase/insights/comment_test.exs | 4 +- test/sanbase/signals/scheduler_test.exs | 3 +- .../trending_words/trending_words_test.exs | 1 - .../graphql/clickhouse/exchanges_test.exs | 8 +- .../historical_balances_test.exs | 32 ++--- .../dev_activity/dev_activity_api_test.exs | 1 - .../graphql/exchanges/market_depth_test.exs | 110 ++++++++---------- .../graphql/exchanges/trades_test.exs | 82 +++++-------- test/sanbase_web/graphql/file_upload_test.exs | 2 +- .../graphql/insight/insight_api_test.exs | 6 +- .../project_api_combined_stats_test.exs | 40 ++++--- .../project_api_eth_spent_over_time_test.exs | 3 - .../projects/project_api_eth_spent_test.exs | 5 +- .../project_api_funds_raised_test.exs | 96 +++++++-------- .../timeline/timeline_event_api_test.exs | 60 +++++++--- .../graphql/user/user_api_test.exs | 23 ++-- .../user/user_eth_account_api_test.exs | 2 +- .../watchlist_historical_stats_api_test.exs | 12 +- test/support/mock.ex | 20 ---- 42 files changed, 315 insertions(+), 314 deletions(-) diff --git a/lib/sanbase/auth/user.ex b/lib/sanbase/auth/user.ex index a11296c52c..b90acfe5e1 100644 --- a/lib/sanbase/auth/user.ex +++ b/lib/sanbase/auth/user.ex @@ -101,15 +101,17 @@ defmodule Sanbase.Auth.User do timestamps() end - def generate_salt do + def generate_salt() do :crypto.strong_rand_bytes(@salt_length) |> Base.url_encode64() |> binary_part(0, @salt_length) end - def generate_email_token do + def generate_email_token() do :crypto.strong_rand_bytes(@email_token_length) |> Base.url_encode64() end def changeset(%User{} = user, attrs \\ %{}) do + attrs = Sanbase.DateTimeUtils.truncate_datetimes(attrs) + user |> cast(attrs, [ :email, @@ -189,15 +191,20 @@ defmodule Sanbase.Auth.User do def san_balance_cache_stale?(%User{san_balance_updated_at: nil}), do: true def san_balance_cache_stale?(%User{san_balance_updated_at: san_balance_updated_at}) do - Timex.diff(Timex.now(), san_balance_updated_at, :seconds) > @san_balance_cache_seconds + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + Timex.diff(naive_now, san_balance_updated_at, :seconds) > @san_balance_cache_seconds end def update_san_balance_changeset(user) do user = Repo.preload(user, :eth_accounts) san_balance = san_balance_for_eth_accounts(user) + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) user - |> change(san_balance: san_balance, san_balance_updated_at: Timex.now()) + |> change( + san_balance_updated_at: naive_now, + san_balance: san_balance + ) end @spec san_balance(%User{}) :: {:ok, float()} | {:ok, nil} | {:error, String.t()} @@ -274,7 +281,7 @@ defmodule Sanbase.Auth.User do user |> change( email_token: generate_email_token(), - email_token_generated_at: Timex.now(), + email_token_generated_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second), email_token_validated_at: nil, consent_id: consent ) @@ -286,44 +293,57 @@ defmodule Sanbase.Auth.User do |> changeset(%{ email_candidate: email_candidate, email_candidate_token: generate_email_token(), - email_candidate_token_generated_at: Timex.now(), + email_candidate_token_generated_at: + NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second), email_candidate_token_validated_at: nil }) |> Repo.update() end def mark_email_token_as_validated(user) do + validated_at = + (user.email_token_validated_at || Timex.now()) + |> Timex.to_naive_datetime() + |> NaiveDateTime.truncate(:second) + user |> change( - email_token_validated_at: user.email_token_validated_at || Timex.now(), + email_token_validated_at: validated_at, is_registered: true ) |> Repo.update() end def update_email_from_email_candidate(user) do + validated_at = + (user.email_candidate_token_validated_at || Timex.now()) + |> Timex.to_naive_datetime() + |> NaiveDateTime.truncate(:second) + user |> changeset(%{ email: user.email_candidate, email_candidate: nil, - email_candidate_token_validated_at: user.email_candidate_token_validated_at || Timex.now() + email_candidate_token_validated_at: validated_at }) |> Repo.update() end def email_token_valid?(user, token) do + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + cond do user.email_token != token -> false - Timex.diff(Timex.now(), user.email_token_generated_at, :minutes) > + Timex.diff(naive_now, user.email_token_generated_at, :minutes) > @login_email_valid_minutes -> false user.email_token_validated_at == nil -> true - Timex.diff(Timex.now(), user.email_token_validated_at, :minutes) > + Timex.diff(naive_now, user.email_token_validated_at, :minutes) > @login_email_valid_after_validation_minutes -> false @@ -333,18 +353,20 @@ defmodule Sanbase.Auth.User do end def email_candidate_token_valid?(user, email_candidate_token) do + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + cond do user.email_candidate_token != email_candidate_token -> false - Timex.diff(Timex.now(), user.email_candidate_token_generated_at, :minutes) > + Timex.diff(naive_now, user.email_candidate_token_generated_at, :minutes) > @login_email_valid_minutes -> false user.email_candidate_token_validated_at == nil -> true - Timex.diff(Timex.now(), user.email_candidate_token_validated_at, :minutes) > + Timex.diff(naive_now, user.email_candidate_token_validated_at, :minutes) > @login_email_valid_after_validation_minutes -> false diff --git a/lib/sanbase/clickhouse/erc20_transfers.ex b/lib/sanbase/clickhouse/erc20_transfers.ex index ba63b688b6..6cd2a727e7 100644 --- a/lib/sanbase/clickhouse/erc20_transfers.ex +++ b/lib/sanbase/clickhouse/erc20_transfers.ex @@ -22,7 +22,7 @@ defmodule Sanbase.Clickhouse.Erc20Transfers do @table "erc20_transfers" @primary_key false - @timestamps_opts updated_at: false + @timestamps_opts [updated_at: false] schema @table do field(:datetime, :utc_datetime, source: :dt) field(:contract, :string, primary_key: true) diff --git a/lib/sanbase/clickhouse/eth_transfers.ex b/lib/sanbase/clickhouse/eth_transfers.ex index 88eb87e8d8..51e4220f36 100644 --- a/lib/sanbase/clickhouse/eth_transfers.ex +++ b/lib/sanbase/clickhouse/eth_transfers.ex @@ -39,7 +39,7 @@ defmodule Sanbase.Clickhouse.EthTransfers do @eth_decimals 1_000_000_000_000_000_000 @primary_key false - @timestamps_opts updated_at: false + @timestamps_opts [updated_at: false] schema @table do field(:datetime, :utc_datetime, source: :dt) field(:from_address, :string, primary_key: true, source: :from) diff --git a/lib/sanbase/clickhouse/github/github.ex b/lib/sanbase/clickhouse/github/github.ex index 3a20f52b9a..ba7e36d563 100644 --- a/lib/sanbase/clickhouse/github/github.ex +++ b/lib/sanbase/clickhouse/github/github.ex @@ -37,7 +37,7 @@ defmodule Sanbase.Clickhouse.Github do @table "github" @primary_key false - @timestamps_opts updated_at: false + @timestamps_opts [updated_at: false] schema @table do field(:datetime, :utc_datetime, source: :dt, primary_key: true) field(:repo, :string, primary_key: true) diff --git a/lib/sanbase/comments/comment.ex b/lib/sanbase/comments/comment.ex index c7ad044ccc..195022cc0a 100644 --- a/lib/sanbase/comments/comment.ex +++ b/lib/sanbase/comments/comment.ex @@ -53,6 +53,8 @@ defmodule Sanbase.Comment do end def changeset(%__MODULE__{} = comment, attrs \\ %{}) do + attrs = Sanbase.DateTimeUtils.truncate_datetimes(attrs) + comment |> cast(attrs, [:user_id, :parent_id, :root_parent_id, :content, :edited_at]) |> validate_required([:user_id, :content]) diff --git a/lib/sanbase/comments/entity_comment.ex b/lib/sanbase/comments/entity_comment.ex index 6d07392771..58aa0a659e 100644 --- a/lib/sanbase/comments/entity_comment.ex +++ b/lib/sanbase/comments/entity_comment.ex @@ -85,11 +85,11 @@ defmodule Sanbase.Comments.EntityComment do end defp apply_cursor(query, %{type: :before, datetime: datetime}) do - from(c in query, where: c.inserted_at < ^datetime) + from(c in query, where: c.inserted_at <= ^(datetime |> DateTime.to_naive())) end defp apply_cursor(query, %{type: :after, datetime: datetime}) do - from(c in query, where: c.inserted_at >= ^datetime) + from(c in query, where: c.inserted_at >= ^(datetime |> DateTime.to_naive())) end defp apply_cursor(query, nil), do: query diff --git a/lib/sanbase/comments/notification.ex b/lib/sanbase/comments/notification.ex index 3951c64bce..ec0a8f6e42 100644 --- a/lib/sanbase/comments/notification.ex +++ b/lib/sanbase/comments/notification.ex @@ -260,7 +260,7 @@ defmodule Sanbase.Comments.Notification do where: p.post_id == ^post_comment.post.id and p.comment_id != ^post_comment.comment.id and - p.inserted_at < ^post_comment.inserted_at, + p.inserted_at <= ^post_comment.inserted_at, preload: [comment: :user] ) end @@ -270,7 +270,7 @@ defmodule Sanbase.Comments.Notification do where: t.timeline_event_id == ^timeline_event_comment.timeline_event.id and t.comment_id != ^timeline_event_comment.comment.id and - t.inserted_at < ^timeline_event_comment.inserted_at, + t.inserted_at <= ^timeline_event_comment.inserted_at, preload: [comment: :user] ) end diff --git a/lib/sanbase/insight/post.ex b/lib/sanbase/insight/post.ex index 709ff5da8f..37c0ec878c 100644 --- a/lib/sanbase/insight/post.ex +++ b/lib/sanbase/insight/post.ex @@ -61,7 +61,7 @@ defmodule Sanbase.Insight.Post do on_delete: :delete_all ) - field(:published_at, :naive_datetime) + field(:published_at, :naive_datetime_usec) timestamps() end diff --git a/lib/sanbase/model/project/roi.ex b/lib/sanbase/model/project/roi.ex index 8cb6f77e07..931fb54660 100644 --- a/lib/sanbase/model/project/roi.ex +++ b/lib/sanbase/model/project/roi.ex @@ -107,12 +107,12 @@ defmodule Sanbase.Model.Project.Roi do ) end - defp calc_token_usd_ico_price(nil, _currency_from, _ico_start_date, _current_datetime), do: nil - defp calc_token_usd_ico_price(_price_from, _currency_from, nil, _current_datetime), do: nil + defp calc_token_usd_ico_price(nil, _currency_from, _ico_start_date, _update_naive_dt), do: nil + defp calc_token_usd_ico_price(_price_from, _currency_from, nil, _update_naive_dt), do: nil defp calc_token_usd_ico_price(_price_from, _currency_from, _ico_start_date, nil), do: nil - defp calc_token_usd_ico_price(price_from, currency_from, ico_start_date, current_datetime) do - with :gt <- Date.compare(current_datetime |> DateTime.to_date(), ico_start_date), + defp calc_token_usd_ico_price(price_from, currency_from, ico_start_date, update_naive_dt) do + with :gt <- Date.compare(update_naive_dt |> NaiveDateTime.to_date(), ico_start_date), datetime <- Sanbase.DateTimeUtils.date_to_datetime(ico_start_date), price_usd when not is_nil(price_usd) <- Sanbase.Price.Utils.fetch_last_price_before(currency_from, "USD", datetime) do diff --git a/lib/sanbase/timeline/cursor.ex b/lib/sanbase/timeline/cursor.ex index 66dc74adb9..58419ca496 100644 --- a/lib/sanbase/timeline/cursor.ex +++ b/lib/sanbase/timeline/cursor.ex @@ -4,14 +4,14 @@ defmodule Sanbase.Timeline.Cursor do def filter_by_cursor(query, :before, datetime) do from( event in query, - where: event.inserted_at < ^datetime + where: event.inserted_at < ^DateTime.to_naive(datetime) ) end def filter_by_cursor(query, :after, datetime) do from( event in query, - where: event.inserted_at > ^datetime + where: event.inserted_at > ^DateTime.to_naive(datetime) ) end diff --git a/lib/sanbase/timeline/timeline_event.ex b/lib/sanbase/timeline/timeline_event.ex index de64e54ca9..b58f3c6746 100644 --- a/lib/sanbase/timeline/timeline_event.ex +++ b/lib/sanbase/timeline/timeline_event.ex @@ -32,7 +32,7 @@ defmodule Sanbase.Timeline.TimelineEvent do @max_events_returned 100 - @timestamps_opts [updated_at: false, type: :utc_datetime] + @timestamps_opts [updated_at: false] @table "timeline_events" schema @table do field(:event_type, :string) @@ -59,6 +59,8 @@ defmodule Sanbase.Timeline.TimelineEvent do def trigger_fired(), do: @trigger_fired def create_changeset(%__MODULE__{} = timeline_events, attrs \\ %{}) do + attrs = Sanbase.DateTimeUtils.truncate_datetimes(attrs) + timeline_events |> cast(attrs, [ :event_type, diff --git a/lib/sanbase/utils/datetime/utils.ex b/lib/sanbase/utils/datetime/utils.ex index 6d0cf64747..4f9b35c189 100644 --- a/lib/sanbase/utils/datetime/utils.ex +++ b/lib/sanbase/utils/datetime/utils.ex @@ -1,4 +1,12 @@ defmodule Sanbase.DateTimeUtils do + def truncate_datetimes(%{} = map, precision \\ :second) do + Enum.into(map, %{}, fn + {k, %DateTime{} = dt} -> {k, DateTime.truncate(dt, precision)} + {k, %NaiveDateTime{} = dt} -> {k, NaiveDateTime.truncate(dt, precision)} + {k, v} -> {k, v} + end) + end + def time_in_range?(%Time{} = time, %Time{} = from, %Time{} = to) do case Time.compare(from, to) do :eq -> diff --git a/lib/sanbase_web/graphql/middlewares/access_control.ex b/lib/sanbase_web/graphql/middlewares/access_control.ex index 998e4a4c42..410338e604 100644 --- a/lib/sanbase_web/graphql/middlewares/access_control.ex +++ b/lib/sanbase_web/graphql/middlewares/access_control.ex @@ -150,7 +150,6 @@ defmodule SanbaseWeb.Graphql.Middlewares.AccessControl do middleware_args ) do if Plan.AccessChecker.is_restricted?(query) do - IO.inspect("#{inspect(query)} IS RESTRICTED????") restricted_query(resolution, middleware_args, query) else not_restricted_query(resolution, middleware_args) diff --git a/lib/sanbase_web/graphql/schema/custom_types/datetime.ex b/lib/sanbase_web/graphql/schema/custom_types/datetime.ex index 30d7abec96..98e5c6a946 100644 --- a/lib/sanbase_web/graphql/schema/custom_types/datetime.ex +++ b/lib/sanbase_web/graphql/schema/custom_types/datetime.ex @@ -16,7 +16,9 @@ defmodule SanbaseWeb.Graphql.CustomTypes.DateTime do |> DateTime.to_iso8601() %DateTime{} = dt -> - DateTime.truncate(dt, :second) |> DateTime.to_iso8601() + dt + |> DateTime.truncate(:second) + |> DateTime.to_iso8601() end) parse(&parse_datetime/1) diff --git a/test/sanbase/auth/user_test.exs b/test/sanbase/auth/user_test.exs index ab9952cdb2..4c3930ff8a 100644 --- a/test/sanbase/auth/user_test.exs +++ b/test/sanbase/auth/user_test.exs @@ -39,17 +39,17 @@ defmodule Sanbase.Auth.UserTest do user = insert(:user, - san_balance: 0, eth_accounts: [%EthAccount{address: "0x000000000001"}], - privacy_policy_accepted: true + san_balance: 100, + san_balance_updated_at: ~N[2020-01-01 00:00:00] ) changeset = User.update_san_balance_changeset(user) assert changeset.changes[:san_balance] == 5.0 - # + assert Sanbase.TestUtils.datetime_close_to( - Timex.now(), + NaiveDateTime.utc_now(), changeset.changes[:san_balance_updated_at], 2, :seconds diff --git a/test/sanbase/clickhouse/api_call_data_test.exs b/test/sanbase/clickhouse/api_call_data_test.exs index 8ce2f0b3ac..740a9be6df 100644 --- a/test/sanbase/clickhouse/api_call_data_test.exs +++ b/test/sanbase/clickhouse/api_call_data_test.exs @@ -1,7 +1,6 @@ defmodule Sanbase.Clickhouse.ApiCallDataTest do use Sanbase.DataCase - import Mock import Sanbase.Factory import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] diff --git a/test/sanbase/clickhouse/gas_used_test.exs b/test/sanbase/clickhouse/gas_used_test.exs index e191b4cd06..038cabbd1a 100644 --- a/test/sanbase/clickhouse/gas_used_test.exs +++ b/test/sanbase/clickhouse/gas_used_test.exs @@ -1,6 +1,5 @@ defmodule Sanbase.Clickhouse.GasUsedTest do use Sanbase.DataCase - import Mock import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] alias Sanbase.Clickhouse.GasUsed diff --git a/test/sanbase/clickhouse/historical_balance/erc20_assets_held_by_address_test.exs b/test/sanbase/clickhouse/historical_balance/erc20_assets_held_by_address_test.exs index 44b4526e5a..41a8a4f5de 100644 --- a/test/sanbase/clickhouse/historical_balance/erc20_assets_held_by_address_test.exs +++ b/test/sanbase/clickhouse/historical_balance/erc20_assets_held_by_address_test.exs @@ -1,7 +1,6 @@ defmodule Sanbase.Clickhouse.HistoricalBalance.Erc20AssetsHeldByAdderssTest do use Sanbase.DataCase - import Mock import Sanbase.Factory alias Sanbase.Clickhouse.HistoricalBalance.Erc20Balance diff --git a/test/sanbase/clickhouse/historical_balance/eth_assets_held_by_address_test.exs b/test/sanbase/clickhouse/historical_balance/eth_assets_held_by_address_test.exs index 9596e56e3f..e0a62bb37b 100644 --- a/test/sanbase/clickhouse/historical_balance/eth_assets_held_by_address_test.exs +++ b/test/sanbase/clickhouse/historical_balance/eth_assets_held_by_address_test.exs @@ -1,7 +1,6 @@ defmodule Sanbase.Clickhouse.HistoricalBalance.EthAssetsHeldByAdderssTest do use Sanbase.DataCase - import Mock import Sanbase.Factory alias Sanbase.Clickhouse.HistoricalBalance.EthBalance diff --git a/test/sanbase/clickhouse/historical_balance/miners_balance_test.exs b/test/sanbase/clickhouse/historical_balance/miners_balance_test.exs index 06064d0150..70c5b459d9 100644 --- a/test/sanbase/clickhouse/historical_balance/miners_balance_test.exs +++ b/test/sanbase/clickhouse/historical_balance/miners_balance_test.exs @@ -1,8 +1,10 @@ defmodule Sanbase.Clickhouse.HistoricalBalance.MinersBalanceTest do use Sanbase.DataCase - import Mock + import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] + alias Sanbase.Clickhouse.HistoricalBalance.MinersBalance + require Sanbase.ClickhouseRepo setup do diff --git a/test/sanbase/clickhouse/metric/clickhouse_metric_helper_test.exs b/test/sanbase/clickhouse/metric/clickhouse_metric_helper_test.exs index 84abae7cdc..c36dec140e 100644 --- a/test/sanbase/clickhouse/metric/clickhouse_metric_helper_test.exs +++ b/test/sanbase/clickhouse/metric/clickhouse_metric_helper_test.exs @@ -1,8 +1,6 @@ defmodule Sanbase.Clickhouse.Metric.HelperTest do use Sanbase.DataCase - import Mock - test "metric id to name map" do rows = [ [1, "daily_active_addresses"], diff --git a/test/sanbase/clickhouse/mining_pools_distribution_test.exs b/test/sanbase/clickhouse/mining_pools_distribution_test.exs index 31a3a06c34..3cbffbe509 100644 --- a/test/sanbase/clickhouse/mining_pools_distribution_test.exs +++ b/test/sanbase/clickhouse/mining_pools_distribution_test.exs @@ -1,8 +1,8 @@ defmodule Sanbase.Clickhouse.MiningPoolsDistributionTest do use Sanbase.DataCase - import Mock - import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] + alias Sanbase.Clickhouse.MiningPoolsDistribution + require Sanbase.ClickhouseRepo setup do diff --git a/test/sanbase/clickhouse/top_holders_test.exs b/test/sanbase/clickhouse/top_holders_test.exs index 975c3d3b16..541341eba1 100644 --- a/test/sanbase/clickhouse/top_holders_test.exs +++ b/test/sanbase/clickhouse/top_holders_test.exs @@ -1,9 +1,11 @@ defmodule Sanbase.Clickhouse.TopHoldersTest do use Sanbase.DataCase - import Mock + import Sanbase.Factory import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] + alias Sanbase.Clickhouse.TopHolders + require Sanbase.ClickhouseRepo setup do diff --git a/test/sanbase/insights/comment_test.exs b/test/sanbase/insights/comment_test.exs index bb1c9f0e9b..f887cc214b 100644 --- a/test/sanbase/insights/comment_test.exs +++ b/test/sanbase/insights/comment_test.exs @@ -43,11 +43,11 @@ defmodule Sanbase.Insight.CommentTest do {:ok, comment} = EntityComment.create_and_link(@entity_type, post.id, post.user_id, nil, content) - naive_dt_before_update = NaiveDateTime.utc_now() + naive_dt_before_update = Timex.shift(NaiveDateTime.utc_now(), seconds: -1) {:ok, updated_comment} = Comment.update(comment.id, comment.user_id, updated_content) - naive_dt_after_update = NaiveDateTime.utc_now() + naive_dt_after_update = Timex.shift(NaiveDateTime.utc_now(), seconds: 1) assert comment.edited_at == nil assert comment.content == content diff --git a/test/sanbase/signals/scheduler_test.exs b/test/sanbase/signals/scheduler_test.exs index a283bcb47d..6c3e3ba156 100644 --- a/test/sanbase/signals/scheduler_test.exs +++ b/test/sanbase/signals/scheduler_test.exs @@ -46,8 +46,7 @@ defmodule Sanbase.Signal.SchedulerTest do project: project, price_usd: 62, user: user, - mock_fun: mock_fun, - mock_chart: [%{image: %{url: "somelink"}}] + mock_fun: mock_fun ] end diff --git a/test/sanbase/social_data/trending_words/trending_words_test.exs b/test/sanbase/social_data/trending_words/trending_words_test.exs index 5a9debec9c..6b2c8120f3 100644 --- a/test/sanbase/social_data/trending_words/trending_words_test.exs +++ b/test/sanbase/social_data/trending_words/trending_words_test.exs @@ -1,7 +1,6 @@ defmodule Sanbase.SocialData.TrendingWordsTest do use Sanbase.DataCase - import Mock import Sanbase.Factory import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1, from_iso8601!: 1] diff --git a/test/sanbase_web/graphql/clickhouse/exchanges_test.exs b/test/sanbase_web/graphql/clickhouse/exchanges_test.exs index 783065ad7b..31e94c09d6 100644 --- a/test/sanbase_web/graphql/clickhouse/exchanges_test.exs +++ b/test/sanbase_web/graphql/clickhouse/exchanges_test.exs @@ -1,10 +1,8 @@ defmodule SanbaseWeb.Graphql.ExchangesTest do use SanbaseWeb.ConnCase, async: false - import Mock import Sanbase.Factory import SanbaseWeb.Graphql.TestHelpers - import Sanbase.DateTimeUtils, only: [from_iso8601_to_unix!: 1] setup do infr = insert(:infrastructure, %{code: "ETH"}) @@ -47,9 +45,9 @@ defmodule SanbaseWeb.Graphql.ExchangesTest do test "test fetching volume for exchange", context do rows = [ - [from_iso8601_to_unix!("2017-05-13T00:00:00Z"), 2000, 1000], - [from_iso8601_to_unix!("2017-05-15T00:00:00Z"), 1800, 1300], - [from_iso8601_to_unix!("2017-05-18T00:00:00Z"), 1000, 1100] + [~U[2017-05-13T00:00:00Z] |> DateTime.to_unix(), 2000, 1000], + [~U[2017-05-15T00:00:00Z] |> DateTime.to_unix(), 1800, 1300], + [~U[2017-05-18T00:00:00Z] |> DateTime.to_unix(), 1000, 1100] ] Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows}}) diff --git a/test/sanbase_web/graphql/clickhouse/historical_balance/historical_balances_test.exs b/test/sanbase_web/graphql/clickhouse/historical_balance/historical_balances_test.exs index a568c3b26b..a953af0d69 100644 --- a/test/sanbase_web/graphql/clickhouse/historical_balance/historical_balances_test.exs +++ b/test/sanbase_web/graphql/clickhouse/historical_balance/historical_balances_test.exs @@ -3,13 +3,9 @@ defmodule SanbaseWeb.Graphql.Clickhouse.HistoricalBalancesTest do import Sanbase.TestHelpers import SanbaseWeb.Graphql.TestHelpers - import Mock - import Sanbase.DateTimeUtils, only: [from_iso8601!: 1] import ExUnit.CaptureLog import Sanbase.Factory - alias Sanbase.DateTimeUtils - require Sanbase.ClickhouseRepo @eth_decimals 1_000_000_000_000_000_000 @@ -29,8 +25,8 @@ defmodule SanbaseWeb.Graphql.Clickhouse.HistoricalBalancesTest do project_with_contract: project_with_contract, project_without_contract: project_without_contract, address: "0x321321321", - from: from_iso8601!("2017-05-11T00:00:00Z"), - to: from_iso8601!("2017-05-20T00:00:00Z"), + from: ~U[2017-05-11T00:00:00Z], + to: ~U[2017-05-20T00:00:00Z], interval: "1d" ] end @@ -54,19 +50,15 @@ defmodule SanbaseWeb.Graphql.Clickhouse.HistoricalBalancesTest do dt3 = ~U[2019-01-03 00:00:00Z] dt4 = ~U[2019-01-04 00:00:00Z] - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:ok, - %{ - rows: [ - [dt1 |> DateTime.to_unix(), :math.pow(10, 18) * 2000, 1], - [dt2 |> DateTime.to_unix(), 0, 0], - [dt3 |> DateTime.to_unix(), 0, 0], - [dt4 |> DateTime.to_unix(), :math.pow(10, 18) * 1800, 1] - ] - }} - end - ) do + rows = [ + [dt1 |> DateTime.to_unix(), :math.pow(10, 18) * 2000, 1], + [dt2 |> DateTime.to_unix(), 0, 0], + [dt3 |> DateTime.to_unix(), 0, 0], + [dt4 |> DateTime.to_unix(), :math.pow(10, 18) * 1800, 1] + ] + + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows}}) + |> Sanbase.Mock.run_with_mocks(fn -> from = dt1 to = dt4 @@ -84,7 +76,7 @@ defmodule SanbaseWeb.Graphql.Clickhouse.HistoricalBalancesTest do historical_balance = result["data"]["historicalBalance"] assert length(historical_balance) == 4 end - end + end) end test "historical balances when interval is bigger than balances values interval", context do diff --git a/test/sanbase_web/graphql/dev_activity/dev_activity_api_test.exs b/test/sanbase_web/graphql/dev_activity/dev_activity_api_test.exs index 0594d58c19..ff6e015fb0 100644 --- a/test/sanbase_web/graphql/dev_activity/dev_activity_api_test.exs +++ b/test/sanbase_web/graphql/dev_activity/dev_activity_api_test.exs @@ -4,7 +4,6 @@ defmodule SanbaseWeb.Graphql.ProjectApiGithubTest do import Mock import Sanbase.Factory import SanbaseWeb.Graphql.TestHelpers - import Sanbase.DateTimeUtils, only: [from_iso8601!: 1] alias Sanbase.Model.Project alias Sanbase.Clickhouse.Github diff --git a/test/sanbase_web/graphql/exchanges/market_depth_test.exs b/test/sanbase_web/graphql/exchanges/market_depth_test.exs index 9d5fb1bccb..9a1774b828 100644 --- a/test/sanbase_web/graphql/exchanges/market_depth_test.exs +++ b/test/sanbase_web/graphql/exchanges/market_depth_test.exs @@ -1,34 +1,24 @@ defmodule SanbaseWeb.Graphql.Exchanges.MarketDepthTest do use SanbaseWeb.ConnCase, async: false - import Mock import SanbaseWeb.Graphql.TestHelpers import ExUnit.CaptureLog test "#last_market_depth", context do - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:ok, - %{ - rows: [result_row()] - }} - end - ) do + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows()}}) + |> Sanbase.Mock.run_with_mocks(fn -> query = last_market_depth_query() result = execute_query(context.conn, query, "lastExchangeMarketDepth") - assert hd(result) == expected_exchange_market_depth() - end + assert List.first(result) == expected_exchange_market_depth() + end) end test "#last_market_depth with error from clickhouse", context do error = "error description" - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:error, error} - end - ) do + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, error}) + |> Sanbase.Mock.run_with_mocks(fn -> query = last_market_depth_query() log = @@ -40,7 +30,7 @@ defmodule SanbaseWeb.Graphql.Exchanges.MarketDepthTest do ~s(Can't fetch Last exchange market depth for exchange and ticker_pair: "Kraken" and "ZEC/BTC", Reason: #{ inspect(error) }) - end + end) end defp expected_exchange_market_depth() do @@ -75,49 +65,51 @@ defmodule SanbaseWeb.Graphql.Exchanges.MarketDepthTest do """ end - defp result_row() do + defp rows() do [ - 1_571_417_428, - "Kraken", - "ZEC/BTC", - 0.00455979, - 0.0012996121796948, - 0.28495291, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - 0.00455005, - 0.7868672411467281, - 173.00153222999998, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil + [ + 1_571_417_428, + "Kraken", + "ZEC/BTC", + 0.00455979, + 0.0012996121796948, + 0.28495291, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + 0.00455005, + 0.7868672411467281, + 173.00153222999998, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil + ] ] end end diff --git a/test/sanbase_web/graphql/exchanges/trades_test.exs b/test/sanbase_web/graphql/exchanges/trades_test.exs index b67c5fef91..520020276b 100644 --- a/test/sanbase_web/graphql/exchanges/trades_test.exs +++ b/test/sanbase_web/graphql/exchanges/trades_test.exs @@ -1,36 +1,28 @@ defmodule SanbaseWeb.Graphql.Exchanges.TradesTest do use SanbaseWeb.ConnCase, async: false - import Mock import SanbaseWeb.Graphql.TestHelpers import ExUnit.CaptureLog test "#last_exchange_trades", context do - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:ok, - %{ - rows: [ - [1_569_704_025, "Kraken", "ETH/EUR", "buy", 2.11604737, 159.63, 337.7846416731] - ] - }} - end - ) do + rows = [ + [1_569_704_025, "Kraken", "ETH/EUR", "buy", 2.11604737, 159.63, 337.7846416731] + ] + + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows}}) + |> Sanbase.Mock.run_with_mocks(fn -> query = last_trades_query() result = execute_query(context.conn, query, "lastExchangeTrades") assert hd(result) == expected_exchange_trade() - end + end) end test "#last_exchange_trades with error from clickhouse", context do error = "error description" - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:error, error} - end - ) do + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, error}) + |> Sanbase.Mock.run_with_mocks(fn -> query = last_trades_query() log = @@ -42,35 +34,28 @@ defmodule SanbaseWeb.Graphql.Exchanges.TradesTest do ~s(Can't fetch Last exchange trades for exchange and ticker_pair: "Kraken" and "ETH/EUR", Reason: #{ inspect(error) }) - end + end) end test "#exchange_trades", context do - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:ok, - %{ - rows: [ - [1_569_704_025, "Kraken", "ETH/EUR", "buy", 2.11604737, 159.63, 337.7846416731] - ] - }} - end - ) do + rows = [ + [1_569_704_025, "Kraken", "ETH/EUR", "buy", 2.11604737, 159.63, 337.7846416731] + ] + + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows}}) + |> Sanbase.Mock.run_with_mocks(fn -> query = trades_query() result = execute_query(context.conn, query, "exchangeTrades") assert hd(result) == expected_exchange_trade() - end + end) end test "#exchange_trades with error from clickhouse", context do error = "error description" - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:error, error} - end - ) do + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, error}) + |> Sanbase.Mock.run_with_mocks(fn -> query = trades_query() log = @@ -82,35 +67,28 @@ defmodule SanbaseWeb.Graphql.Exchanges.TradesTest do ~s(Can't fetch Exchange trades for exchange and ticker_pair: "Kraken" and "ETH/EUR", Reason: #{ inspect(error) }) - end + end) end test "#aggregated exchange_trades", context do - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:ok, - %{ - rows: [ - [1_569_704_025, 2.11604737, 159.63, 337.7846416731, "buy"] - ] - }} - end - ) do + rows = [ + [1_569_704_025, 2.11604737, 159.63, 337.7846416731, "buy"] + ] + + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: rows}}) + |> Sanbase.Mock.run_with_mocks(fn -> query = aggregated_trades_query() result = execute_query(context.conn, query, "exchangeTrades") assert hd(result) == expected_exchange_trade() - end + end) end test "#aggregated exchange_trades with error from clickhouse", context do error = "error description" - with_mock(Sanbase.ClickhouseRepo, - query: fn _, _ -> - {:error, error} - end - ) do + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, error}) + |> Sanbase.Mock.run_with_mocks(fn -> query = aggregated_trades_query() log = @@ -122,7 +100,7 @@ defmodule SanbaseWeb.Graphql.Exchanges.TradesTest do ~s(Can't fetch Aggregated exchange trades for exchange and ticker_pair: "Kraken" and "ETH/EUR", Reason: #{ inspect(error) }) - end + end) end defp expected_exchange_trade() do diff --git a/test/sanbase_web/graphql/file_upload_test.exs b/test/sanbase_web/graphql/file_upload_test.exs index 6952769a84..f0a7dd9b97 100644 --- a/test/sanbase_web/graphql/file_upload_test.exs +++ b/test/sanbase_web/graphql/file_upload_test.exs @@ -12,7 +12,7 @@ defmodule SanbaseWeb.Graphql.FileUploadTest do %User{ salt: User.generate_salt(), san_balance: Decimal.mult(Decimal.new(10), Sanbase.SantimentContract.decimals_expanded()), - san_balance_updated_at: Timex.now(), + san_balance_updated_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second), privacy_policy_accepted: true } |> Repo.insert!() diff --git a/test/sanbase_web/graphql/insight/insight_api_test.exs b/test/sanbase_web/graphql/insight/insight_api_test.exs index 209b792ec0..fc345a66b3 100644 --- a/test/sanbase_web/graphql/insight/insight_api_test.exs +++ b/test/sanbase_web/graphql/insight/insight_api_test.exs @@ -664,7 +664,8 @@ defmodule SanbaseWeb.Graphql.InsightApiTest do insert(:post, user: user, ready_state: Post.published(), - updated_at: Timex.shift(Timex.now(), seconds: -1) + updated_at: + Timex.shift(NaiveDateTime.utc_now(), seconds: -1) |> NaiveDateTime.truncate(:second) ) mutation = """ @@ -687,8 +688,9 @@ defmodule SanbaseWeb.Graphql.InsightApiTest do updated_at = Sanbase.DateTimeUtils.from_iso8601!(result["data"]["updateInsight"]["updatedAt"]) + |> DateTime.to_naive() - assert DateTime.compare(updated_at, post.updated_at) == :gt + assert NaiveDateTime.compare(updated_at, post.updated_at) == :gt end test "can update tags for published insight", %{conn: conn, user: user} do diff --git a/test/sanbase_web/graphql/projects/project_api_combined_stats_test.exs b/test/sanbase_web/graphql/projects/project_api_combined_stats_test.exs index 72b43d5e85..4912d7e534 100644 --- a/test/sanbase_web/graphql/projects/project_api_combined_stats_test.exs +++ b/test/sanbase_web/graphql/projects/project_api_combined_stats_test.exs @@ -34,37 +34,47 @@ defmodule SanbaseWeb.Graphql.ProjectApiCombinedStatsTest do fn -> result = get_history_stats(conn, from, to, slugs) - assert result == %{ - "data" => %{ - "projectsListHistoryStats" => [ - %{"datetime" => "2017-05-13T00:00:00Z", "marketcap" => 545, "volume" => 220}, - %{"datetime" => "2017-05-14T00:00:00Z", "marketcap" => 2000, "volume" => 1400}, - %{"datetime" => "2017-05-15T00:00:00Z", "marketcap" => 2600, "volume" => 1600} - ] + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: data}}) + |> Sanbase.Mock.run_with_mocks(fn -> + assert result == %{ + "data" => %{ + "projectsListHistoryStats" => [ + %{"datetime" => "2017-05-13T00:00:00Z", "marketcap" => 545, "volume" => 220}, + %{ + "datetime" => "2017-05-14T00:00:00Z", + "marketcap" => 2000, + "volume" => 1400 + }, + %{ + "datetime" => "2017-05-15T00:00:00Z", + "marketcap" => 2600, + "volume" => 1600 + } + ] + } } - } + end) end - |> Sanbase.Mock.with_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: data}}) end test "the database returns no data", context do %{conn: conn, from: from, to: to, slugs: slugs} = context - fn -> + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: []}}) + |> Sanbase.Mock.run_with_mocks(fn -> result = get_history_stats(conn, from, to, slugs) assert result == %{"data" => %{"projectsListHistoryStats" => []}} - end - |> Sanbase.Mock.with_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: []}}) + end) end test "the database returns an error", context do %{conn: conn, from: from, to: to, slugs: slugs} = context - fn -> + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, "Database error"}) + |> Sanbase.Mock.run_with_mocks(fn -> %{"errors" => [error]} = get_history_stats(conn, from, to, slugs) assert error["message"] =~ "Cannot get combined history stats for a list of slugs." - end - |> Sanbase.Mock.with_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, "Database error"}) + end) end defp get_history_stats(conn, from, to, slugs) do diff --git a/test/sanbase_web/graphql/projects/project_api_eth_spent_over_time_test.exs b/test/sanbase_web/graphql/projects/project_api_eth_spent_over_time_test.exs index c6c63ff6b3..d4a196b1ef 100644 --- a/test/sanbase_web/graphql/projects/project_api_eth_spent_over_time_test.exs +++ b/test/sanbase_web/graphql/projects/project_api_eth_spent_over_time_test.exs @@ -1,13 +1,10 @@ defmodule SanbaseWeb.Graphql.ProjectApiEthSpentOverTimeTest do use SanbaseWeb.ConnCase, async: false - import Mock import Sanbase.TestHelpers import SanbaseWeb.Graphql.TestHelpers import Sanbase.Factory - alias Sanbase.DateTimeUtils - @eth_decimals 1_000_000_000_000_000_000 setup do diff --git a/test/sanbase_web/graphql/projects/project_api_eth_spent_test.exs b/test/sanbase_web/graphql/projects/project_api_eth_spent_test.exs index 28e268bb36..f243da1e5b 100644 --- a/test/sanbase_web/graphql/projects/project_api_eth_spent_test.exs +++ b/test/sanbase_web/graphql/projects/project_api_eth_spent_test.exs @@ -1,7 +1,6 @@ defmodule SanbaseWeb.Graphql.ProjecApiEthSpentTest do use SanbaseWeb.ConnCase, async: false - import Mock import Sanbase.Factory import Sanbase.TestHelpers import SanbaseWeb.Graphql.TestHelpers @@ -15,9 +14,9 @@ defmodule SanbaseWeb.Graphql.ProjecApiEthSpentTest do eth_infr = insert(:infrastructure, %{code: "ETH"}) - project = insert(:random_erc20_project) + project = insert(:random_erc20_project, infrastructure: eth_infr) - project_address = p.eth_addresses |> List.first() + project_address = project.eth_addresses |> List.first() [ project: project, diff --git a/test/sanbase_web/graphql/projects/project_api_funds_raised_test.exs b/test/sanbase_web/graphql/projects/project_api_funds_raised_test.exs index 935c5c2fc4..bb1f9cdb08 100644 --- a/test/sanbase_web/graphql/projects/project_api_funds_raised_test.exs +++ b/test/sanbase_web/graphql/projects/project_api_funds_raised_test.exs @@ -40,49 +40,45 @@ defmodule SanbaseWeb.Graphql.ProjectApiFundsRaisedTest do test "fetch project funds raised", context do %{conn: conn, project: project} = context - expected_result = %{ - "name" => project.name, - "fundsRaisedBtcIcoEndPrice" => 72.5, - "fundsRaisedEthIcoEndPrice" => 390.0, - "fundsRaisedUsdIcoEndPrice" => 1950.0, - "icos" => [ - %{ - "endDate" => "2017-08-19", - "fundsRaisedBtcIcoEndPrice" => 32.5, - "fundsRaisedEthIcoEndPrice" => 190.0, - "fundsRaisedUsdIcoEndPrice" => 950.0 - }, - %{ - "endDate" => "2017-10-17", - "fundsRaisedEthIcoEndPrice" => 200.0, - "fundsRaisedUsdIcoEndPrice" => 1.0e3, - "fundsRaisedBtcIcoEndPrice" => 40.0 - } - ] - } - - fn -> + Sanbase.Mock.prepare_mock(Sanbase.Price, :last_record_before, fn slug, datetime -> + if DateTime.compare(datetime, context.datetime) == :lt do + case slug do + "bitcoin" -> {:ok, %{price_usd: 2, price_btc: 0.1, marketcap: 100, volume: 100}} + "test" -> {:ok, %{price_usd: 4, price_btc: 0.05, marketcap: 100, volume: 100}} + "ethereum" -> {:ok, %{price_usd: 5, price_btc: 0.2, marketcap: nil, volume: nil}} + end + else + case slug do + "bitcoin" -> {:ok, %{price_usd: 5, price_btc: 0.2, marketcap: 100, volume: 100}} + "test" -> {:ok, %{price_usd: 4, price_btc: 0.03, marketcap: 100, volume: 100}} + "ethereum" -> {:ok, %{price_usd: 10, price_btc: 0.8, marketcap: 100, volume: 100}} + end + end + end) + |> Sanbase.Mock.run_with_mocks(fn -> result = get_funds_raised(conn, project) |> get_in(["data", "projectBySlug"]) - assert result == expected_result - end - |> Sanbase.Mock.with_mock2( - {Sanbase.Price, :last_record_before, - fn slug, datetime -> - if DateTime.compare(datetime, context.datetime) == :lt do - case slug do - "bitcoin" -> {:ok, %{price_usd: 2, price_btc: 0.1, marketcap: 100, volume: 100}} - "test" -> {:ok, %{price_usd: 4, price_btc: 0.05, marketcap: 100, volume: 100}} - "ethereum" -> {:ok, %{price_usd: 5, price_btc: 0.2, marketcap: nil, volume: nil}} - end - else - case slug do - "bitcoin" -> {:ok, %{price_usd: 5, price_btc: 0.2, marketcap: 100, volume: 100}} - "test" -> {:ok, %{price_usd: 4, price_btc: 0.03, marketcap: 100, volume: 100}} - "ethereum" -> {:ok, %{price_usd: 10, price_btc: 0.8, marketcap: 100, volume: 100}} - end - end - end} - ) + + assert result == %{ + "name" => project.name, + "fundsRaisedBtcIcoEndPrice" => 72.5, + "fundsRaisedEthIcoEndPrice" => 390.0, + "fundsRaisedUsdIcoEndPrice" => 1950.0, + "icos" => [ + %{ + "endDate" => "2017-08-19", + "fundsRaisedBtcIcoEndPrice" => 32.5, + "fundsRaisedEthIcoEndPrice" => 190.0, + "fundsRaisedUsdIcoEndPrice" => 950.0 + }, + %{ + "endDate" => "2017-10-17", + "fundsRaisedEthIcoEndPrice" => 200.0, + "fundsRaisedUsdIcoEndPrice" => 1.0e3, + "fundsRaisedBtcIcoEndPrice" => 40.0 + } + ] + } + end) end test "no ico does not break query", context do @@ -92,15 +88,13 @@ defmodule SanbaseWeb.Graphql.ProjectApiFundsRaisedTest do get_funds_raised(conn, project) |> get_in(["data", "projectBySlug"]) - expected_result = %{ - "name" => project.name, - "fundsRaisedUsdIcoEndPrice" => nil, - "fundsRaisedEthIcoEndPrice" => nil, - "fundsRaisedBtcIcoEndPrice" => nil, - "icos" => [] - } - - assert result == expected_result + assert result == %{ + "name" => project.name, + "fundsRaisedUsdIcoEndPrice" => nil, + "fundsRaisedEthIcoEndPrice" => nil, + "fundsRaisedBtcIcoEndPrice" => nil, + "icos" => [] + } end # Private functions diff --git a/test/sanbase_web/graphql/timeline/timeline_event_api_test.exs b/test/sanbase_web/graphql/timeline/timeline_event_api_test.exs index b61ad7a361..40dfd0519b 100644 --- a/test/sanbase_web/graphql/timeline/timeline_event_api_test.exs +++ b/test/sanbase_web/graphql/timeline/timeline_event_api_test.exs @@ -98,8 +98,10 @@ defmodule SanbaseWeb.Graphql.TimelineEventApiTest do assert result |> hd() |> Map.get("events") |> hd() |> Map.get("data") == nil assert result |> hd() |> Map.get("cursor") == %{ - "after" => DateTime.to_iso8601(DateTime.truncate(event3.inserted_at, :second)), - "before" => DateTime.to_iso8601(DateTime.truncate(event1.inserted_at, :second)) + "after" => + DateTime.to_iso8601(event3.inserted_at |> DateTime.from_naive!("Etc/UTC")), + "before" => + DateTime.to_iso8601(event1.inserted_at |> DateTime.from_naive!("Etc/UTC")) } end @@ -502,29 +504,43 @@ defmodule SanbaseWeb.Graphql.TimelineEventApiTest do {trigger1, trigger2, trigger3} = create_trigger(context) - insight_event = - insert(:timeline_event, - post: post, - user: context.user, - event_type: TimelineEvent.publish_insight_type() - ) - generic_setting_trigger_event = %{ user_trigger: nil, user: context.user, event_type: TimelineEvent.trigger_fired(), payload: %{"default" => "some signal payload"}, - data: %{"user_trigger_data" => %{"default" => %{"value" => 15}}} + data: %{"user_trigger_data" => %{"default" => %{"value" => 15}}}, + inserted_at: NaiveDateTime.utc_now() } + insight_event = + insert(:timeline_event, + post: post, + user: context.user, + event_type: TimelineEvent.publish_insight_type(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -4) + ) + trigger1_event = - insert(:timeline_event, %{generic_setting_trigger_event | user_trigger: trigger1}) + insert(:timeline_event, %{ + generic_setting_trigger_event + | user_trigger: trigger1, + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -3) + }) trigger2_event = - insert(:timeline_event, %{generic_setting_trigger_event | user_trigger: trigger2}) + insert(:timeline_event, %{ + generic_setting_trigger_event + | user_trigger: trigger2, + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -2) + }) trigger3_event = - insert(:timeline_event, %{generic_setting_trigger_event | user_trigger: trigger3}) + insert(:timeline_event, %{ + generic_setting_trigger_event + | user_trigger: trigger3, + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -1) + }) create_test_events(context) @@ -668,28 +684,32 @@ defmodule SanbaseWeb.Graphql.TimelineEventApiTest do insert(:post, user: user_to_follow, state: Post.approved_state(), - ready_state: Post.published() + ready_state: Post.published(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -10) ) post2 = insert(:post, user: san_author2, state: Post.approved_state(), - ready_state: Post.published() + ready_state: Post.published(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -9) ) post3 = insert(:post, user: san_author2, state: Post.approved_state(), - ready_state: Post.published() + ready_state: Post.published(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -8) ) event_with_0_votes_and_1_comments_by_followed = insert(:timeline_event, post: post1, user: user_to_follow, - event_type: TimelineEvent.publish_insight_type() + event_type: TimelineEvent.publish_insight_type(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -7) ) EntityComment.create_and_link( @@ -704,7 +724,8 @@ defmodule SanbaseWeb.Graphql.TimelineEventApiTest do insert(:timeline_event, post: post2, user: san_author2, - event_type: TimelineEvent.publish_insight_type() + event_type: TimelineEvent.publish_insight_type(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -6) ) Sanbase.Vote.create(%{ @@ -716,7 +737,8 @@ defmodule SanbaseWeb.Graphql.TimelineEventApiTest do insert(:timeline_event, post: post3, user: san_author2, - event_type: TimelineEvent.publish_insight_type() + event_type: TimelineEvent.publish_insight_type(), + inserted_at: Timex.shift(NaiveDateTime.utc_now(), seconds: -5) ) %{ diff --git a/test/sanbase_web/graphql/user/user_api_test.exs b/test/sanbase_web/graphql/user/user_api_test.exs index b7f3f4177f..0f54e50064 100644 --- a/test/sanbase_web/graphql/user/user_api_test.exs +++ b/test/sanbase_web/graphql/user/user_api_test.exs @@ -236,11 +236,12 @@ defmodule SanbaseWeb.Graphql.UserApiTest do |> Repo.insert!() |> User.update_email_candidate("example+foo@santiment.net") + generated_at = + Timex.shift(NaiveDateTime.utc_now(), days: -2) |> NaiveDateTime.truncate(:second) + user = user - |> Ecto.Changeset.change( - email_candidate_token_generated_at: Timex.shift(Timex.now(), days: -2) - ) + |> Ecto.Changeset.change(email_candidate_token_generated_at: generated_at) |> Repo.update!() query = """ @@ -414,9 +415,11 @@ defmodule SanbaseWeb.Graphql.UserApiTest do |> Repo.insert!() |> User.update_email_token() + generated_at = Timex.shift(Timex.now(), days: -2) |> NaiveDateTime.truncate(:second) + user = user - |> Ecto.Changeset.change(email_token_generated_at: Timex.shift(Timex.now(), days: -2)) + |> Ecto.Changeset.change(email_token_generated_at: generated_at) |> Repo.update!() query = """ @@ -447,11 +450,13 @@ defmodule SanbaseWeb.Graphql.UserApiTest do |> Repo.insert!() |> User.update_email_token() + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + user = user |> Ecto.Changeset.change( - email_token_generated_at: Timex.now(), - email_token_validated_at: Timex.now() + email_token_generated_at: naive_now, + email_token_validated_at: naive_now ) |> Repo.update!() @@ -488,11 +493,13 @@ defmodule SanbaseWeb.Graphql.UserApiTest do |> Repo.insert!() |> User.update_email_token() + naive_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + user = user |> Ecto.Changeset.change( - email_token_generated_at: Timex.now(), - email_token_validated_at: Timex.shift(Timex.now(), minutes: -20) + email_token_generated_at: naive_now, + email_token_validated_at: Timex.shift(naive_now, minutes: -20) ) |> Repo.update!() diff --git a/test/sanbase_web/graphql/user/user_eth_account_api_test.exs b/test/sanbase_web/graphql/user/user_eth_account_api_test.exs index 37df57d1f6..442ae4bcd9 100644 --- a/test/sanbase_web/graphql/user/user_eth_account_api_test.exs +++ b/test/sanbase_web/graphql/user/user_eth_account_api_test.exs @@ -87,7 +87,7 @@ defmodule SanbaseWeb.Graphql.UserEthAccountApiTest do result = add_eth_address(context.conn, @address) %{"errors" => [error]} = result assert error["message"] == "Could not add an ethereum address." - end) =~ ~s/[address: {"has already been taken", []}]/ + end) =~ ~s/[address: {"has already been taken"/ end # Helper functions diff --git a/test/sanbase_web/graphql/watchlist/watchlist_historical_stats_api_test.exs b/test/sanbase_web/graphql/watchlist/watchlist_historical_stats_api_test.exs index 6d938c6833..5b0357ac19 100644 --- a/test/sanbase_web/graphql/watchlist/watchlist_historical_stats_api_test.exs +++ b/test/sanbase_web/graphql/watchlist/watchlist_historical_stats_api_test.exs @@ -81,11 +81,11 @@ defmodule SanbaseWeb.Graphql.WatchlistHistoricalStatsApiTest do } } - fn -> + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: data}}) + |> Sanbase.Mock.run_with_mocks(fn -> result = get_watchlist_historical_stats(conn, from, to, watchlist) assert result == expected_result - end - |> Sanbase.Mock.with_mock2(&Sanbase.ClickhouseRepo.query/2, {:ok, %{rows: data}}) + end) end test "empty watchlist", context do @@ -100,11 +100,11 @@ defmodule SanbaseWeb.Graphql.WatchlistHistoricalStatsApiTest do test "the database returns an errors", context do %{conn: conn, from: from, to: to, watchlist: watchlist} = context - fn -> + Sanbase.Mock.prepare_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, "Clickhouse error"}) + |> Sanbase.Mock.run_with_mocks(fn -> %{"errors" => [error]} = get_watchlist_historical_stats(conn, from, to, watchlist) assert error["message"] =~ "Can't fetch historical stats for a watchlist." - end - |> Sanbase.Mock.with_mock2(&Sanbase.ClickhouseRepo.query/2, {:error, "Clickhouse error"}) + end) end defp get_watchlist_historical_stats(conn, from, to, watchlist) do diff --git a/test/support/mock.ex b/test/support/mock.ex index 46bc418ecf..37729a49ba 100644 --- a/test/support/mock.ex +++ b/test/support/mock.ex @@ -43,26 +43,6 @@ defmodule Sanbase.Mock do end end - def with_mock2(assert_fun, {module, fun_name, fun_body}) do - with_mock(module, [{fun_name, fun_body}], do: assert_fun.()) - end - - for arity <- 0..16 do - @arity arity - - def with_mock2(assert_fun, captured_fun, data) - when is_function(captured_fun, unquote(arity)) do - {:name, name} = Function.info(captured_fun, :name) - {:module, module} = Function.info(captured_fun, :module) - - fun = fn unquote_splicing(Macro.generate_arguments(@arity, __MODULE__)) -> - data - end - - with_mock(module, [{name, fun}], do: assert_fun.()) - end - end - def init(), do: MapSet.new() def prepare_mock(state \\ MapSet.new(), module, fun_name, fun_body, opts \\ [])