globalSetup to reference baseUrl from playwright.config - playwright

Im currently using a global-setup.ts file to load a url via playwright.
await page.goto('https://test1.com/');
I am also doing extra code inside here and storing the state of my object (All works as expected)
My playwright.config.ts file references the globalsetup and this all works as expected.
In my Config file I also set baseUrl however, I am struggling on a way to get the baseUrl passed to my global-setup.ts file instead of hardcoding it.
Thanks!

Inside your global setup, you can access the baseURL like that:
import { FullConfig } from '#playwright/test';
async function globalSetup(config: FullConfig) {
console.log(config.projects[0].use.baseURL);
}
export default globalSetup
See here: https://playwright.dev/docs/api/class-testconfig/

Related

Using Futures to load config.json in Flutter

Being new to Dart/Flutter I am using this snippet to try and load a config.json file that I have stored in my assets folder. In trying to read this file, I am using models on the Dart language Futures documentation and in the Flutter docs on reading local text files:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
Future<List> loadAsset() async {
String raw = await rootBundle.loadString('assets/config.json');
List configData = json.decode(raw);
return configData;
}
Then, inside my class, I try to load the config into a List, like this:
Future<List> configData = loadAsset();
print(configData.toString());
// prints out: Instance of 'Future<List<dynamic>>'
The result of all this seems to work. Yet I can find no way of using the data I have loaded. Any effort to access elements in the List, e.g. configData[0] results in an error:
The following _CompileTimeError was thrown building
HomePage(dirty, state: HomePageState#b1af8):
'package:myapp/pages/home_page.dart': error:
line 64 pos 19: lib/pages/home_page.dart:64:19:
Error: The method '[]' isn't defined for the class
'dart.async::Future<dart.core::List<dynamic>>'.
Try correcting the name to the name of an existing method,
or defining a method named '[]'.
I would like to convert the configData Future into a normal object that I can read and pass around my app. I am able to do something very similar, and to get it to work inside a widget's build method, using a FutureBuilder and the DefaultAssetBundle thus...
DefaultAssetBundle
.of(context)
.loadString('assets/config.json')
...but I don't want the overhead of reloading the data inside all the widgets that need it. I would like to load inside a separate Dart package and have it available as a global configuration across all my app. Any pointers would be appreciated.
I have tried the suggestion by Rémi Rousselet:
List configData = await loadAsset();
print(configData[0]);
In this case, I get a compiler error:
compiler message: lib/pages/home_page.dart:55:21: Error: Getter not found: 'await'.
compiler message: List configData = await loadAsset();
compiler message: ^^^^^
You can't do configData[0] as configData is not a List but a Future.
Instead, await the future to have access to the List inside
List configData = await loadAsset();
print(configData[0]);
You can only use await INSIDE async methods.
If you want to you your assets in entire application you want to load the asset in the main method similar like this.
void main() async {
StorageUtils.localStorage = await SharedPreferences.getInstance();
}
Now you can use localStorage synchronously in entire application and you don't need to deal with another asynchronous calls or load it again.
Different example, same principle.

Dart has a standard way to externalize settings like Java properties?

I'm looking for the right way to externalize the settings in my server Dart application.
In Java the common way would be a property file. Exists something similar in Dart?
You can just use a Dart script for your settings. No point in using a different format if there is no specific reason.
With a simple import you have it available in a typed way.
When the Resource class is implemented, I would just use a JSON file that is deployed with my program.
You could use a global variables, for example:
DB_URL = 'localhost:5432/mydb';
DB_PASS = 'my_pass';
then you could create a different configuration file for every enviroment. For example, for production you could create a production_config.dart which could contains:
loadConfig() {
DB_URL = '123.123.123.123:5432/mydb';
DB_PASS = 'my_prod_pass';
}
Then in your main function you could call production_config.loadConfig if environment is production, for example:
import 'production_config.dart' as prodConfig;
main(List<String> args) {
var ENV = getEnvFromArgs(args);
if(ENV == 'PROD') {
prodConfig.loadConfig();
}
//do other stuff here
}
In that way if you want to change from development to production you only need to pass an argument to your dart program for example:
dart myprogram.dart -env=PROD
The advantages of this approach are that you don't need to create a separate properties, json or yaml file for this, and you don't need to parse them. Furthermore the properties are type-ckecked.
I like putting configuration in a Dart class like what Günter Zöchbauer was talking about, but there is also the option of using the safe_config package. With this you enter the values in a yaml file. Quoting from the docs:
You define a subclass of Configuration with those properties:
class ApplicationConfiguration extends Configuration {
ApplicationConfiguration(String fileName) :
super.fromFile(File(fileName));
int port;
String serverHeader;
}
Your YAML file should contain those two, case-sensitive keys:
port: 8000
serverHeader: booyah/1
To read your configuration file:
var config = new ApplicationConfiguration("config.yaml");
print("${config.port}"); // -> 8000
print("${config.serverHeader}"); // -> "booyah/1"
See also an example from a setup in Aqueduct.
main() {
var env = const String.fromEnvironment("ENV", defaultValue: "local");
print("Env === " + env);
}
Give environment as option while running Dart App
pub serve --port=9002 --define ENV=dev
References:
http://blog.sethladd.com/2013/12/compile-time-dead-code-elimination-with.html
https://github.com/dart-lang/sdk/issues/27998

How to read file from an imported library

I have two packages: webserver and utils which provides assets to webserver.
The webserver needs access to static files inside utils. So I have this setup:
utils/
lib/
static.html
How can I access the static.html file in one of my dart scripts in webserver?
EDIT: What I tried so far, is to use mirrors to get the path of the library, and read it from there. The problem with that approach is, that if utils is included with package:, the url returned by currentMirrorSystem().findLibrary(#utils).uri is a package uri, that can't be transformed to an actual file entity.
Use the Resource class, a new class in Dart SDK 1.12.
Usage example:
var resource = new Resource('package:myapp/myfile.txt');
var contents = await resource.loadAsString();
print(contents);
This works on the VM, as of 1.12.
However, this doesn't directly address your need to get to the actual File entity, from a package: URI. Given the Resource class today, you'd have to route the bytes from loadAsString() into the HTTP server's Response object.
I tend to use Platform.script or mirrors to find the main package top folder (i.e. where pubspec.yaml is present) and find imported packages exported assets. I agree this is not a perfect solution but it works
import 'dart:io';
import 'package:path/path.dart';
String getProjectTopPath(String resolverPath) {
String dirPath = normalize(absolute(resolverPath));
while (true) {
// Find the project root path
if (new File(join(dirPath, "pubspec.yaml")).existsSync()) {
return dirPath;
}
String newDirPath = dirname(dirPath);
if (newDirPath == dirPath) {
throw new Exception("No project found for path '$resolverPath");
}
dirPath = newDirPath;
}
}
String getPackagesPath(String resolverPath) {
return join(getProjectTopPath(resolverPath), 'packages');
}
class _TestUtils {}
main(List<String> arguments) {
// User Platform.script - does not work in unit test
String currentScriptPath = Platform.script.toFilePath();
String packagesPath = getPackagesPath(currentScriptPath);
// Get your file using the package name and its relative path from the lib folder
String filePath = join(packagesPath, "utils", "static.html");
print(filePath);
// use mirror to find this file path
String thisFilePath = (reflectClass(_TestUtils).owner as LibraryMirror).uri.toString();
packagesPath = getPackagesPath(thisFilePath);
filePath = join(packagesPath, "utils", "static.html");
print(filePath);
}
To note that since recently Platform.script is not reliable in unit test when using the new test package so you might use the mirror tricks that I propose above and explained here: https://github.com/dart-lang/test/issues/110

Create a file relative path for secure server certificate

I'm working on a Dart HttpServer using SSL, which looks something like this:
class Server {
//The path for the database is relative to the code's entry point (main.dart)
static const String CERTIFICATE_DB_PATH = '../lib/server/';
static const String CERTIFICATE_DB_PASS = '*******';
static const String CERTIFICATE_NAME = 'CN=mycert';
Future start() async {
SecureSocket.initialize(database: CERTIFICATE_DB_PATH, password: CERTIFICATE_DB_PASS);
httpServer = await HttpServer.bindSecure(ADDRESS, PORT, certificateName: CERTIFICATE_NAME);
listenSubscription = httpServer.listen(onRequest, onError: onError);
}
//more server code here
}
This all works exactly as expected, so no problems with the actual certificate or server code. The part that I'm having problems with is mentioned in that first comment. The CERTIFICATE_DB_PATH seems to be relative not to the file the Server class is defined in, but rather to the file that contains the main() method. This means that when I try to write a unit test for this class, the path is no longer pointing to the correct directory. If this were an import, I'd use the package:packageName/path/to/cert syntax, but it doesn't seem that applies here. How can I specify the path of the certificate in a way that will work with multiple entry points (actually running the server vs unit tests)?
I don't think there is a way to define the path so it is relative to the source file.
What you can do is to change the current working directory either before you run main() or pass a working directory path as argument to main() and let main() make this directory the current working directory.
Directory.current = someDirectory;

How to create a custom yaml config file in Symfony

What I want to do is quite simple: store data in a custom config file that I want to read later on.
I created my file something.yml that I put in the global config directory.
It looks like that:
prod:
test: ok
dev:
test: ko
all:
foo: bar
john: doe
Then I copied the config_handlers.yml and also put it in the config directory and added the following at the top of the file:
config/something.yml:
class: sfDefineEnvironmentConfigHandler
param:
prefix: something_
But if I'm calling sfConfig::get("something_foo"); I keep getting NULL.
What did I do wrong?
I just want to read values, so no need to create a custome config handler, right?
I've read the doc here: http://www.symfony-project.org/book/1_2/19-Mastering-Symfony-s-Configuration-Files even though I'm running 1.4 (I don't think that changed since then).
Edit: Of course I can use sfYaml::load() but I'd like to do things in a better way.
Do not modify the index.php this is dirty!
Juste add this line to your app/frontend/config/frontendConfiguration.class.php
require_once($this->getConfigCache()->checkConfig('config/something.yml'));
(adapt with your own app name)
It's really easy, but also a little bit hacky:
Create the file /config/config_handlers.yml and add this:
config/something.yml:
class: sfDefineEnvironmentConfigHandler
param:
prefix: something_
Then add these two lines to /web/index.php after ... getApplicationConfiguration() (and also add them to frontend_dev.php and wherever you want this config file to be available):
$configCache = new sfConfigCache($configuration);
include($configCache->checkConfig('config/something.yml'));
So your /web/index.php might look like this afterwards:
<?php
require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false);
$configCache = new sfConfigCache($configuration);
$configCache->checkConfig('config/something.yml');
sfContext::createInstance($configuration)->dispatch();
Btw: This is also in the documentation you cited, although the checkConfig() call is in a different place. Look for this: "When you need the code based on the map.yml file and generated by the myMapConfigHandler handler in your application, call the following line:"
Have fun ;-)
If you're doing this for a plugin you need to load the configuration file in the initialize() method. You can still use config_handlers.yml in your plugin's config directory or let the plugin load the handler too.
class myPluginConfiguration extends sfPluginConfiguration
{
public function setup() // loads handler if needed
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
$configCache = $this->configuration->getConfigCache();
$configCache->registerConfigHandler('config/features.yml', 'sfDefineEnvironmentConfigHandler',
array('prefix' => 'feature_'));
$configCache->checkConfig('config/features.yml');
}
}
public function initialize() // loads the actual config file
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
$configCache = $this->configuration->getConfigCache();
include($configCache->checkConfig('config/features.yml'));
}
}
}
The plugin's config initialize() method is called automatically by sfProjectConfiguration class and all appConfiguration classes (trough inheritance).
if your cached config-file is empty, you have probably forgotten to set the environment in your yml-file.
like:
all:
test: value1
test2: value2
dev:
test2: value3
Works in all application files:
$configCache = sfApplicationConfiguration::getActive()->getConfigCache();
$configCache->registerConfigHandler('config/something.yml', 'sfDefineEnvironmentConfigHandler', Array('prefix' => 'something_'));
include $configCache->checkConfig('config/something.yml');
Then you can use:
sfConfig::get("something_foo");
Have you cleared your cache files?
php symfony cc
In prodution environment all config files, classes, etc... are being cached.

Resources