btcpayserver/BTCPayServer.Tests/Extensions.cs

224 lines
7.8 KiB
C#
Raw Normal View History

2020-06-29 04:44:35 +02:00
using System;
using System.Diagnostics;
2019-10-12 13:35:30 +02:00
using System.Text;
using System.Threading;
2019-05-12 07:51:24 +02:00
using System.Threading.Tasks;
using BTCPayServer.Services.Wallets;
2019-05-14 12:13:55 +02:00
using BTCPayServer.Tests.Logging;
2019-05-12 07:51:24 +02:00
using Microsoft.AspNetCore.Mvc;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OpenQA.Selenium;
Bootstrap v5 migration (#2490) * Swap bootstrap asset files * Update themes and color definitions * Move general bootstrap customizations * Theme updates Theme updates * Remove BuildBundlerMinifier This lead to an error, because BuildBundlerMinifier and BundlerMinifier.Core seem to conflict here. Details: https://stackoverflow.com/a/61119586 * Rewplace btn-block class with w-100 * Update badge classes * Remove old font family head variable * Update margin classes * Cleanups * Update float classes * Update text classes * Update padding classes * Update border classes * UPdate dropdown classes * Update select classes * Update neutral custom props * Update bootstrap and customizations * Update ChromeDriver; disable smooth scroll https://github.com/SeleniumHQ/selenium/issues/8295 * Improve alert messages * Improve bootstrap customizations * Disable reduced motion See also 7358282f * Update Bootstrap data attributes * Update file inputs * Update input groups * Replace deprecated jumbotron class * Update variables; re-add negative margin util classes * Update cards * Update form labels * Debug alerts * Fix aria-labelledby associations * Dropdown-related test fixes * Fix CanUseWebhooks test * Test fixes * Nav updates * Fix nav usage in wallet send and payouts * Update alert and modal close buttons * Re-add backdrop properties * Upgrade Bootstrap to v5 final * Update screen reader classes * Update font-weight classes * Update monospace font classes * Update accordians * Update close icon usage * Cleanup * Update scripts and style integrations * Update input group texts * Update LN node setup page * Update more form control classes * Update inline forms * Add js specific test * Upgrade Vue.js * Remove unused JS * Upgrade Bootstrap to v5.0.1 * Try container related test updates * Separate jQuery bundle * Remove jQuery from LND seed backup page * Remove unused code * Refactor email autofill js * Refactor camera scanner JS * Re-add tests * Re-add BuildBundlerMinifier * Do not minify bundles containing Bootstrap Details https://github.com/madskristensen/BundlerMinifier/issues/558 * Update bundles * Cleanup JS test * Cleanup tests involving dropdowns * Cleanup tests involving collapses * Cleanup locale additions in ConfigureCore * Cleanup bundles * Remove duplicate status message * Cleanup formatting * Fix missing validation scripts * Remove unused unminified Bootstrap js files * Fix classic theme * Fix Casa theme * Fix PoS validation
2021-05-19 04:39:27 +02:00
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
2019-05-12 07:51:24 +02:00
using Xunit;
namespace BTCPayServer.Tests
{
public static class Extensions
{
public static Task<KeyPathInformation> ReserveAddressAsync(this BTCPayWallet wallet, DerivationStrategyBase derivationStrategyBase)
{
return wallet.ReserveAddressAsync(null, derivationStrategyBase, "test");
}
2021-01-25 14:10:19 +01:00
private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
public static string ToJson(this object o) => JsonConvert.SerializeObject(o, Formatting.None, JsonSettings);
2021-01-14 10:57:17 +01:00
public static void LogIn(this SeleniumTester s, string email)
2021-01-14 10:57:17 +01:00
{
s.Driver.FindElement(By.Id("Email")).SendKeys(email);
s.Driver.FindElement(By.Id("Password")).SendKeys("123456");
s.Driver.FindElement(By.Id("LoginButton")).Click();
s.Driver.AssertNoError();
2021-01-14 10:57:17 +01:00
}
public static void AssertNoError(this IWebDriver driver)
{
if (driver.PageSource.Contains("alert-danger"))
{
foreach (var dangerAlert in driver.FindElements(By.ClassName("alert-danger")))
Assert.False(dangerAlert.Displayed, $"No alert should be displayed, but found this on {driver.Url}: {dangerAlert.Text}");
}
Assert.DoesNotContain("errors", driver.Url);
Assert.DoesNotContain("Error", driver.Title, StringComparison.OrdinalIgnoreCase);
}
2021-12-31 08:59:02 +01:00
2019-05-12 07:51:24 +02:00
public static T AssertViewModel<T>(this IActionResult result)
{
Assert.NotNull(result);
var vr = Assert.IsType<ViewResult>(result);
return Assert.IsType<T>(vr.Model);
}
public static async Task<T> AssertViewModelAsync<T>(this Task<IActionResult> task)
{
var result = await task;
Assert.NotNull(result);
var vr = Assert.IsType<ViewResult>(result);
return Assert.IsType<T>(vr.Model);
}
2021-09-28 04:22:35 +02:00
// Sometimes, selenium is flaky...
public static IWebElement FindElementUntilNotStaled(this IWebDriver driver, By by, Action<IWebElement> act)
2021-09-28 04:22:35 +02:00
{
2021-12-31 08:59:02 +01:00
retry:
2021-09-28 04:22:35 +02:00
try
{
var el = driver.FindElement(by);
act(el);
return el;
2021-09-28 04:22:35 +02:00
}
catch (StaleElementReferenceException)
{
goto retry;
}
}
2019-10-12 13:35:30 +02:00
public static void AssertElementNotFound(this IWebDriver driver, By by)
{
2019-10-12 13:35:30 +02:00
DateTimeOffset now = DateTimeOffset.Now;
var wait = SeleniumTester.ImplicitWait;
while (DateTimeOffset.UtcNow - now < wait)
{
2019-10-12 13:35:30 +02:00
try
{
var webElement = driver.FindElement(by);
if (!webElement.Displayed)
return;
}
2020-03-11 16:51:33 +01:00
catch (NoSuchWindowException)
{
return;
}
2019-10-12 13:35:30 +02:00
catch (NoSuchElementException)
{
return;
}
Thread.Sleep(50);
}
Assert.Fail("Elements was found");
}
public static void UntilJsIsReady(this WebDriverWait wait)
{
2021-12-31 08:59:02 +01:00
wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return typeof(jQuery) === 'undefined' || jQuery.active === 0").Equals(true));
}
2021-12-31 08:59:02 +01:00
Bootstrap v5 migration (#2490) * Swap bootstrap asset files * Update themes and color definitions * Move general bootstrap customizations * Theme updates Theme updates * Remove BuildBundlerMinifier This lead to an error, because BuildBundlerMinifier and BundlerMinifier.Core seem to conflict here. Details: https://stackoverflow.com/a/61119586 * Rewplace btn-block class with w-100 * Update badge classes * Remove old font family head variable * Update margin classes * Cleanups * Update float classes * Update text classes * Update padding classes * Update border classes * UPdate dropdown classes * Update select classes * Update neutral custom props * Update bootstrap and customizations * Update ChromeDriver; disable smooth scroll https://github.com/SeleniumHQ/selenium/issues/8295 * Improve alert messages * Improve bootstrap customizations * Disable reduced motion See also 7358282f * Update Bootstrap data attributes * Update file inputs * Update input groups * Replace deprecated jumbotron class * Update variables; re-add negative margin util classes * Update cards * Update form labels * Debug alerts * Fix aria-labelledby associations * Dropdown-related test fixes * Fix CanUseWebhooks test * Test fixes * Nav updates * Fix nav usage in wallet send and payouts * Update alert and modal close buttons * Re-add backdrop properties * Upgrade Bootstrap to v5 final * Update screen reader classes * Update font-weight classes * Update monospace font classes * Update accordians * Update close icon usage * Cleanup * Update scripts and style integrations * Update input group texts * Update LN node setup page * Update more form control classes * Update inline forms * Add js specific test * Upgrade Vue.js * Remove unused JS * Upgrade Bootstrap to v5.0.1 * Try container related test updates * Separate jQuery bundle * Remove jQuery from LND seed backup page * Remove unused code * Refactor email autofill js * Refactor camera scanner JS * Re-add tests * Re-add BuildBundlerMinifier * Do not minify bundles containing Bootstrap Details https://github.com/madskristensen/BundlerMinifier/issues/558 * Update bundles * Cleanup JS test * Cleanup tests involving dropdowns * Cleanup tests involving collapses * Cleanup locale additions in ConfigureCore * Cleanup bundles * Remove duplicate status message * Cleanup formatting * Fix missing validation scripts * Remove unused unminified Bootstrap js files * Fix classic theme * Fix Casa theme * Fix PoS validation
2021-05-19 04:39:27 +02:00
// Open collapse via JS, because if we click the link it triggers the toggle animation.
// This leads to Selenium trying to click the button while it is moving resulting in an error.
public static void ToggleCollapse(this IWebDriver driver, string collapseId)
{
driver.ExecuteJavaScript($"document.getElementById('{collapseId}').classList.add('show')");
}
2021-12-31 08:59:02 +01:00
public static void SetAttribute(this IWebDriver driver, string element, string attribute, string value)
{
driver.ExecuteJavaScript($"document.getElementById('{element}').setAttribute('{attribute}', '{value}')");
}
public static void InvokeJSFunction(this IWebDriver driver, string element, string funcName)
{
driver.ExecuteJavaScript($"document.getElementById('{element}').{funcName}()");
}
public static void WaitWalletTransactionsLoaded(this IWebDriver driver)
{
var wait = new WebDriverWait(driver, SeleniumTester.ImplicitWait);
wait.UntilJsIsReady();
wait.Until(d => d.WaitForElement(By.CssSelector("#WalletTransactions[data-loaded='true']")));
}
public static IWebElement WaitForElement(this IWebDriver driver, By selector)
{
var wait = new WebDriverWait(driver, SeleniumTester.ImplicitWait);
wait.UntilJsIsReady();
var el = driver.FindElement(selector);
wait.Until(d => el.Displayed);
return el;
}
Checkout v2 finetuning (#4276) * Indent all JSON files with two spaces * Upgrade Vue.js * Cheat mode improvements * Show payment details in case of expired invoice * Add logo size recommendation * Show clipboard copy hint cursor * Improve info area and wording * Update BIP21 wording * Invoice details adjustments * Remove form; switch payment methods via AJAX * UI updates * Decrease paddings to gain space * Tighten up padding between logo mark and the store title text * Add drop-shadow to the containers * Wording * Cheating improvements * Improve footer spacing * Cheating improvements * Display addresses * More improvements * Expire invoices * Customize invoice expiry * Footer improvements * Remove theme switch * Remove non-existing sourcemap references * Move inline JS to checkout.js file * Plugin compatibility See Kukks/btcpayserver#8 * Test fix * Upgrade vue-i18next * Extract translations into a separate file * Round QR code borders * Remove "Pay with Bitcoin" title in BIP21 case * Add copy hint to payment details * Cheating: Reduce margins * Adjust dt color * Hide addresses for first iteration * Improve View Details button * Make info section collapsible * Revert original en locale file * Checkout v2 tests * Result view link fixes * Fix BIP21 + lazy payment methods case * More result page link improvements * minor visual improvements * Update clipboard code Remove fallback for old browsers. https://caniuse.com/?search=navigator.clipboard * Transition copy symbol * Update info text color * Invert dark neutral colors Simplifies the dark theme quite a bit. * copy adjustments * updates QR border-radius * Add option to remove logo * More checkout v2 test cases * JS improvements * Remove leftovers * Update test * Fix links * Update tests * Update plugins integration * Remove obsolete url code * Minor view update * Update JS to not use arrow functions * Remove FormId from Checkout Appearance settings * Add English-only hint and feedback link * Checkout Appearance: Make options clearer, remove Custom CSS for v2 * Clipboard copy full URL instead of just address/BOLT11 * Upgrade JS libs, add content checks * Add test for BIP21 setting with zero amount invoice Co-authored-by: dstrukt <gfxdsign@gmail.com>
2022-11-24 00:53:32 +01:00
public static void FillIn(this IWebElement el, string text)
{
el.Clear();
el.SendKeys(text);
}
2022-03-01 19:39:25 +01:00
public static void ScrollTo(this IWebDriver driver, IWebElement element)
{
driver.ExecuteJavaScript("arguments[0].scrollIntoView();", element);
}
public static void ScrollTo(this IWebDriver driver, By selector)
{
2022-03-01 19:39:25 +01:00
ScrollTo(driver, driver.FindElement(selector));
}
2022-06-02 10:08:55 +02:00
public static void WaitUntilAvailable(this IWebDriver driver, By selector, TimeSpan? waitTime = null)
{
// Try fast path
2022-06-02 10:08:55 +02:00
var wait = new WebDriverWait(driver, SeleniumTester.ImplicitWait);
try
{
2022-06-02 10:08:55 +02:00
var el = driver.FindElement(selector);
wait.Until(_ => el.Displayed && el.Enabled);
return;
}
catch { }
// Sometimes, selenium complain, so we enter hack territory
wait.UntilJsIsReady();
2021-10-31 06:20:31 +01:00
int retriesLeft = 4;
retry:
2021-10-31 06:20:31 +01:00
try
{
var el = driver.FindElement(selector);
2022-06-02 10:08:55 +02:00
wait.Until(_ => el.Displayed && el.Enabled);
driver.ScrollTo(selector);
2022-06-02 10:08:55 +02:00
driver.FindElement(selector);
2021-10-31 06:20:31 +01:00
}
2022-06-02 10:08:55 +02:00
catch (NoSuchElementException) when (retriesLeft > 0)
2021-10-31 06:20:31 +01:00
{
retriesLeft--;
if (waitTime != null)
Thread.Sleep(waitTime.Value);
2021-10-31 06:20:31 +01:00
goto retry;
}
wait.UntilJsIsReady();
}
2022-06-02 10:08:55 +02:00
public static void WaitForAndClick(this IWebDriver driver, By selector)
{
driver.WaitUntilAvailable(selector);
driver.FindElement(selector).Click();
}
2022-06-28 16:58:03 +02:00
public static bool ElementDoesNotExist(this IWebDriver driver, By selector)
{
Assert.Throws<NoSuchElementException>(
[DebuggerStepThrough]
() =>
2022-06-28 16:58:03 +02:00
{
driver.FindElement(selector);
});
return true;
}
public static bool SetCheckbox(this IWebDriver driver, By selector, bool value)
{
var element = driver.FindElement(selector);
if (value != element.Selected)
{
driver.WaitForAndClick(selector);
return true;
}
return false;
}
2019-05-12 07:51:24 +02:00
}
}