Property based testing in Java with kqwik

There are a couple (maybe more) libraries for property based testing, I found that jqwik worked well for me.

I’m not going to go too deep into what property based testing is, except to state that for my purposes, property based testing allows me to generate random values to pass into my tests. I can generate multiple “tries” or items of data and even restrict ranges of values.

Specifically I’m using property based testing to generate values for some unit conversion code, the values get converted to a different unit and back – if the resultant value is the same as the input value we can assume that the conversion back and forth works correctly.

Anyway there are plenty of resources to read on the subject, so let’s get stuck into some code.

First off we need the following dependency to our pom.xml (obviously change the version to suit)

<dependency>
  <groupId>net.jqwik</groupId>
  <artifactId>jqwik</artifactId>
  <version>1.6.2</version>
  <scope>test</scope>
</dependency>

Let’s look a an example unit test

@Property(tries = 100)
public void testFromDegreesToGradiansAndBack(@ForAll @DoubleRange(min = -1E12, max = 1E12) double value) {
  final double convertTo = Angle.Degrees.toGradians(value);
  final double convertBack = Angle.Gradians.toDegrees(convertTo);
  assertEquals(value, convertBack, 0.01);
}

The @Property annotation tells the jqik runner to supply data for the method, creating 100 items of data (or tries) and @ForAll is used to assign data to the double value. Finally for this test I wanted to constrain the range of double values to [-1E12, 1E12].

The output (upon success) looks similar to this

timestamp = 2022-01-05T20:00:08.038391600, AngleTests:testFromDegreesToGradiansAndBack = 
                              |--------------------jqwik--------------------
tries = 100                   | # of calls to property
checks = 100                  | # of not rejected calls
generation = RANDOMIZED       | parameters are randomly generated
after-failure = PREVIOUS_SEED | use the previous seed
when-fixed-seed = ALLOW       | fixing the random seed is allowed
edge-cases#mode = MIXIN       | edge cases are mixed in
edge-cases#total = 7          | # of all combined edge cases
edge-cases#tried = 6          | # of edge cases tried in current run
seed = -3195058119397656120   | random seed to reproduce generated values

Errors will cause the test to fail and output the failure for you to review.

Cargo

As part of a little project I’m working on, I’m back playing within Rust.

Whilst we can use rustc to build our code we’re more likely to use the build and package management application cargo. Let’s take a look at the core features of using cargo.

What version are you running?

To find the version of cargo, simply type

cargo --version

Creating a new project

Cargo can be used to create a minimal project which will include the .toml configuration file and the code will be written to a src folder. Cargo expects a specific layout of configuration and source as well as writing the building artifacts to the target folder.

To generate a minimal application run the following (replacing app_name with your application name)

cargo new app_name

We can also use cargo to create a minimal library using the –lib switch

cargo new lib_name --lib

Building our project

To build the project artifacts, run the following from the root of your application/library

cargo build

This command will create the binaries in the target folder. This is (by default) a debug build, to create a release build ass the –release switch i.e.

cargo build --release

Running our project

In the scenarios where we’ve generated an executable, then we can run the application by cd-ing into the target folder and running the .exe or via cargo we use

cargo run

Check your build

In some cases, where you are not really interested in generating an executable (for example) you can run the check command which will simply verify your code is valid – this will likely be faster than generating the executable and is useful where you just want to ensure your code will build

cargo check

Creating Mac icons with GIMP

When developing for iOS, the OS handles the masking of the image to give it a rounded rectangle look, but for the Mac icons this does not currently appear to happen. The icon asset set expects 16×16, 32×32, 64×64, 128×128, 256×256, 512×512 and 1024×1024 square images (they also require 16×16@2 and so on, i.e. 2x the images up to but not including 1024×1024).

If you supply a full sized squared image, as per the stated dimensions, no mask is supplied and hence the icons looks much larger than the standard Mac ones and also lack the style of them (i.e. rounded corners).

This post is basically about creating icons that look more the part using GIMP.

  • Create a 1024×1024 image
  • Add an Alpha Layer
  • Select All of the image and clear it
  • Create a second image around 880×880 in size – you might want it larger or smaller depending on the icon but you’re really aiming to have the actual icon smaller than the full image size.
  • Now we want to round the image, in GIMP select the Select | Rounded Rectangle option and set the Radius to 42% or you might prefer to right mouse click on the image and select Filters | Decor and then Round Corners (the former will not add any drop shadow whereas the second will.
  • You may want to remove the background by inverting the selection then Edit | Clear or simply copy/cut the selected and round image and copy to the larger image we created
  • You may need to align the image using Tools | Transform Tools and Align (or short cut Q)

That’s about it – experiment with the radius % and size of the image as I’m not sure I have them as perfect replicas of the Mac standard icons, but they’re a lot close than a full sized image.

Creating a console app. in Swift (on Linux)(part 2)

In my post Creating a console app. in Swift (on Linux) I demonstrated creating a console app. using Swift. I used top level statement to create the application, but there’s another way.

Note: Those familiar with C# will see how C# now offers both the traditional class based Program as well as top level statement style, well Swift offers similar.

After creating your application using

swift package init --type executable

Create a file in the Sources folder named App.swift or whatever you like except I found that main.swift didn’t seem to work and caused errors such as error: ‘main’ attribute cannot be used in a module that contains top-level code.

Now in your App.swift paste the following

@main
struct App {
    static func main() {
        print("Hello World")
    }
}

Note: The @main attribute is important to mark the type as the main application code.

If you now use the following from the command line, you should see Hello World output.

swift run

Erlang modules and functions

Modules

Modules are (what you might expect) a way to group together functions.

We declare a module with the first line

-module(Name).

This is always the first line of a module and the Name is an atom (an atom being a literal/constant).

Next up in our module, we’ll be exporting functions along with their arity (arity being an integer representing the number of arguments that can be passed to the function). So for example, if we have add with two arguments we would export it like this

-export([add/2]).

We can export multiple functions within the -export for example

-export([add/2, delete/2, multiply/2, divide/2]).

So let’s put those pieces together and we get a math module something like this

-module(math).
-export([add/2, subtract/2, multiply/2, divide/2]).

add(A, B) -> 
    A + B.

subtract(A, B) -> 
    A - B.

multiply(A, B) -> 
    A * B.

divide(A, B) -> 
    A / B.

Functions

So we’ve seen some example of functions, let’s look at the syntax.

Functions take the form Name(Args) -> Body. where each expression in the body ends with a comma, so for example

start() -> 
    S = "Hello World",
    io:fwrite(S).

Publishing Dart packages to pub.dev

Dart packages can be published to pub.dev and it’s a pretty simple process.

  • 1. Sign up to create an account on pub.dev
  • 2. Don’t worry about the Publisher, you can create and upload packages without this

Next up, let’s assume you don’t yet have a package yet – check out Creating packages to learn about the expected project layout of folders/files. We can simply run the following Dart command to create the template for us

dart create -t package-simple mypackage

Obviously change the mypackage name to that of your package.

Before we look into the requirements for publishing, let’s just state that pub.dev (when you publish your package) runs some analysis across your package and assigns you PUB POINTS – for example to follow Dart file conventions you’re expected to supply a valid pubspec.yaml, a valid README.md and a valid CHANGELOG.md.

  • Update the pubspec.yaml description field – ensure it has 60-180 characters
  • The package created by the Dart CLI gives a good starting point for the README.md and CHANGELOG.md – don’t forget to update the CHANGELOG.md to match each version
  • Implement your code in the lib/src folder – files should use lowercase, snakecase, or you’ll lose PUB POINTS
  • Ensure you’re lib .dart file has
    library mypackage;
    

    Replacing mypackage with your package name if you change the package name at any point during development.

  • Add your tests to the test folder
  • Add an example to the example folder
  • Ensure your code has doc comments to your lib .dart file as well as to the lib/src files, i.e.
    /// My Doc Comments
    

Assuming you’ve got everything in place, run

dart format .

to adhere to Dart formatting preferences. You’ll lose PUB POINTS if you publish with format issues.

Ensure your tests all run successfully using

dart test

Run the publish process in dry-run mode using

dart pub publish --dry-run

When ready, run

dart pub publish

You can exclude files from publishing by prefixing the filenames with a ., any directory with the name packages is ignored. Finally, files and directories within .pubignore or .gitignore are also excluded.

If I recall when publishing, you may be asked to log into pub.dev – just follow the publish command’s prompts and if all went well you’ll have the package upload to pub.dev.

Remember, once you’ve published a package it cannot be deleted, but you can mark them as discontinued. So make sure you have your package named as your want it to be (at the very least) before you publish it.

Ensure versions are correct and updated each time you publish, along with CHANGELOG.md updates to show what happened for each new version.

Finally pub.dev will run it’s analyse process and then supply a PUB POINT score out of 130 and will give information on what’s missing or needs attention to get a 130/130 score – for example, my current package needs a couple of files formatting correctly and an example as I didn’t use the package template but wrote mine from scratch.

Lastly, try to get your README.md etc. right before publishing as you’ll have to increment the version of your app just to change the README.md (yes I learned the hard way).

NLog embedding runtime variables

Sometimes you’ll want to set your NLog configuration up to output the log files to an environment, i.e. %APPDATA%/MyApp/Logging/UAT – but you’ll only know the selected environment at runtime.

This is where we can embed ${var:NAME}, where NAME is a key to your variable. In our case this will be ENV for environment.

So for example, let’s assume we have this fileName in your NLog configuration like this

fileName="${specialfolder:folder=ApplicationData}/MyApp/Logging/${var:ENV}/logfile_{$shortdate}.log

As you can see from the above, we’ve included the built-in specialfolder and shortdate variables. For the ${var:ENV} we need to supply using “env” variable in our code, for example

LogManager.Configurations.Variables["env"] = GetCurrentEnvironment()

Use Powershell to change file date/time stamps

Ever wanted to change the creation date/time on a file on Windows – Powershell offers the following (change Filename.ext to your filename)

$(Get-Item Filename.ext).creationtime
$(Get-Item Filename.ext).lastwritetime
$(Get-Item Filename.ext).lastaccesstime

Want to change these? You can supply the date in a string like this

$(Get-Item Filename.ext).creationtime = "15 March 2022 19:00:00"
$(Get-Item Filename.ext).lastwritetime = "15 March 2022 19:00:00"
$(Get-Item Filename.ext).lastaccesstime = "15 March 2022 19:00:00"

or if you like you’ve got

$(Get-Item Filename.ext).creationtime = $(Get-Date)
$(Get-Item Filename.ext).creationtime = $(Get-Date "15/03/2022 19:00:00")

Note: I’m on a en-GB machine hence using dd/MM/yyyy format – ofcourse changes this to your culture format.

Stopping my Ubuntu server from hibernating

I’m not sure what’s happened, but after a recent upgrade to my Ubuntu server – when I tried to connect to the server (which I use as both a dev server and NAS), I couldn’t log into via ssh but when I attached a monitor and keyboard to the server I was able to use it and the ssh started working. However after a period of inactivity the server seemingly went offline, pressing the power switch briefly bought it back online. So some how it had gone sleep/hibernate mode – not very useful thing for a server.

Here’s some steps I went through to eventually get this working again…

Check the logs

Checking the logs is always a useful first step, so let’s take a look at the syslog

nano /var/log/syslog

or use

tail -f /var/log/syslog

I spotted log entries saying the machine was going to sleep.

Checking and then disabling sleep mode

Now use systemctl to confirm the status of the sleep.target, i.e. is it enabled

sudo systemctl status sleep.target

To disable sleep, we probably want to disable all options that hibernate/sleep so we can disable the lot using

sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target

If for some reason you wish to re-enable these, just run

sudo systemctl unmask sleep.target suspend.target hibernate.target hybrid-sleep.target

I’m still none the wiser as to how hibernate got enabled – but at least I’ve learned how to check and disable it.

Dart web server

I know, when you think Dart you possibly think Flutter, i.e. mobile UI. However Dart is not limited to mobile. Let’s create a simple webserver using shelf 1.2.0.

First off, create a folder for our code and in there create a file with the name pubspec.yaml. This is used to store our dependencies. In this file we have the following

name: server

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  shelf: ^1.2.0
  shelf_router: ^1.0.0
  shelf_static: ^1.0.0

The ‘name’ is the name of your app – I am not being very inspiring calling mine server.

Now we’ll just copy and paste the example from Shelf. So create a file named server.dart (the name doesn’t matter, again, I was uninspiring in my choice).

So server.dart should contain the following (I’ve changed from localhost to 0.0.0.0 to access the site from another computer as this code is hosted on a headless server).

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() async {
  var handler =
      const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest);

  var server = await shelf_io.serve(handler, '0.0.0.0', 8080);

  // Enable content compression
  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Response _echoRequest(Request request) =>
    Response.ok('Request for "${request.url}"');

Next we’ll want to update/get the packages, so run

dart pub get

Finally let’s run the server using

dart server.dart

If all went well a server is run up on port 8080 and accessible via your preferred web browser. This simple example can be accessed using the following (for example)

http://192.168.1.1:8080/hello

hello is just used to get a response from the server, which will look like this Request for “hello”.

Routing

The above gives us a baseline to work from. We’re going to want to route requests to alternate functions, currently requests simple go to the _echoRequest function.

We’ve actually already added the shelf_router to our pubspec, so just import the package and add the Router. We’re going to removing the handler and the _echoRequest function, so our main function looks like this now

import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() async {

  var app = Router();

  app.get('/hello', (Request request) {
    return Response.ok('hello-world');
  });

  app.get('/user/<user>', (Request request, String user) {
    return Response.ok('hello $user');
  });

  var server = await shelf_io.serve(app, '0.0.0.0', 8080);

  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Note: This code is basically a copy of the example on shelf_router.