marcusoft.net - sharing is learning


function share(knowledge){ return share(++knowledge) }

Testing WebAPI with AspNetCore.Mvc.Testing and xUnit Collections


I’m writing a boot camp for .NET core and have started to learn a lot of things that have changed since I last coded C#. One of them was shown to me by my good friend John Magnusson. (I’m downplaying his knowledge and skills a lot here since I was close to tears and he sent me a link that saved by bacon, but hey - I’m telling the story :))

Anyhow - John showed me Microsoft.AspNetCore.Mvc.Testing that really tells a nice story when it comes to testing an API. In this post I wanted to show you how I used it.

Also - I ran into problems, since I had a database seeding that didn’t work when I used the suggested solution. I will show you how I solved that too, and in the process, tell you a little thing I picked up about xUnit. And a bit about how to set up a singleton in ASP.NET Web Api.

Phew - that’s a truckload. Let’s go! I hope you’ll learn as much as I did.

Read on ...

xUnit - closing Selenium driver after ALL test in suite


I’m enjoying myself at work right now, writing a course in C# and for the .NET core platform. Man - this was some time ago.

Naturally I learn a lot. That’s why I became a teacher. I wanted to share a little nugget (NuGet?) of gold that I found.

In one of the early labs in the course I used Selenium to write some end-to-end tests. And in doing so I need to create Driver object, that is both pretty heavy to start and, if left after the test run, quickly will eat your memory.

Now, I was using xUnit as my testing framework and xUnit doesn’t have a notion of test suites. This was bad since I wanted to create the Driver object on the first e2e test and not tear it down until the last.

My intial attempt looked like this:

using System;
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace Salt.Stars.End2End
{
  public class Index_E2E_Tests : IDisposable
  {
    IWebDriver Driver = null;
    public Index_E2E_Tests()
    {
      Driver = new ChromeDriver();
    }

    public void Dispose()
    {
      if (Driver != null)
      {
        Driver.Quit();
        Driver = null;
      }
    }

    [Fact]
    public void Test1()
    {
      // Arrange
      var testName = "Marcus";

      // Act
      Driver.Navigate().GoToUrl($"http://localhost:6001/?developerName={testName}");

      // Assert
      IWebElement mainHeader = Driver.FindElement(By.Id("mainHeader"));
      Assert.Contains(testName, mainHeader.Text);
    }
  }
}

Which was not too bad, this will now create the Driver object before the first test is run in the file, and dispose of the Driver object after the tests in this file.

But I soon ended up with several files like that and I saw 6 Chrome Browsers open. I just need one for all tests in the E2E-suite.

Fix for the fixture

This StackOverflow post taught me that there’s a way to create a disposable fixture like this:

public class BrowserFixture : IDisposable
{
  public IWebDriver Driver { get; private set; }
  public BrowserFixture()
  {
    Driver = new ChromeDriver();
  }

  public void Dispose()
  {
    if (Driver != null)
    {
      Driver.Quit();
      Driver = null;
    }
  }
}

This is cool - I now have a fixture that is disposed, and it also becomes a little bit like a context for my browser automation tests. Maybe I’ll have more stuff in there.

We now need to tell our tests about this fixture. This is done in two steps. First we create a CollectionFixture out of our fixture. This is the way that xUnit can group tests together in a … collection or suite.

[CollectionDefinition("Browser automation collection")]
public class BrowserCollection : ICollectionFixture<BrowserFixture>
{
}

Yes - no code in there. It’s a marker interface that we will use soon. Now, in fact:

[Collection("Browser automation collection")]
public class Index_E2E_Tests
{
  IWebDriver _driver = null;
  public Index_E2E_Tests(BrowserFixture browserFixture)
  {
    _driver = browserFixture.Driver;
  }

  [Fact]
  public void Index_Page_Shows_without_name()
  {
    // Act
    _driver.Navigate().GoToUrl($"http://localhost:6001/");

    // Assert
    IWebElement mainHeader = _driver.FindElement(By.Id("mainHeader"));
    Assert.Contains("Get your greeting below", mainHeader.Text);
  }
}

The important points happens outside of the tests:

  • We mark the class with the [Collection] attribute, giving it a name so that we can group things into a collection with the same name.
  • Our constructor now gets a parameter of the BrowserFixture type that we created before. How? Well, when we defined the collection fixture we gave it the type ICollectionFixture<BrowserFixture> and hence can get the fixture of the correct type.
  • From that we can then pull the Driver or what ever thing we have exposed.

We don’t need to dispose the object in our test, that is done after all the tests in the [Collection("Browser automation collection")] is run

Nice!

Read on ...

A data-driven prognosis report


I have a big project ahead here at Salt - I’m going to write an entire boot camp from scratch. This is done as a single-person project and all my other colleagues are working on as normal around me.

I wanted to report my progress to them so that they know what’s happening and also that I can get some leeway of keeping my focus.

In this post, I wanted to share a very simple prognosis tool that I created based on the data that my work create. As always, it’s not perfect but it will give an accurate enough feel for where I am and when it will be done

Read on ...

Writing a Selenium test using .NET core and Visual Studio Code


I’m rediscovering my first programming love; .NET. I’m having a blast and .NET core keeps giving.

This post is one of those - I can’t believe that I couldn’t find this post on the net somewhere. Or I didn’t look hard enough.

But I wanted to setup Selnium testing, but only use .NET Core and Visual Studio Code on my Mac. Every example I saw was using older versions of .NET core (I’m writing this on .NET core 5) and/or Visual Studio, which I don’t have.

Read on ...

Making boring fun - bash and Node to the rescue


I rarely get paid to write code these days… or that is people rarely ask me to write code. But since I’m a programmer at heart it is one of the tools in my toolbelt, regardless of what kind of tasks I’m given.

Today I got asked:

Could you please list all Open Source Licenses we are using, and all the dependencies all our code is using.

Considering we have 130+ repositories I was what the scientist refer to as a boring task.

Let’s make it more fun with code.

Read on ...

When I learned a safety lesson - and did a little bit better


I like to automate repetitive and boring things I do in my daily work. This lead to that me write bash scripts from time to time, but the problem is that I’m a newbie scripter. I’m learning as I go.

And the other day I did a cardinal sin in scripting. Not only that - I decided to show the world. Now that is a point to feel ashamed or to learn. I did both.

In this post, I will tell you about how I made my curl-script a little better and a lot safer, but using an old way that’s been in curl for ages.

Read on ...

Introducing ScrAdd - the script adder


I’ve been increasingly annoyed with the fact there’s no easy way to add scripts to a package.json file programmatically. It always messes up my lovely scripts for tutorial setups and other use cases. Very frustrating.

Well … until not that is.

I give you ScrAdd - the script adder.

Let’s say that you are writing a tutorial on how to test next apps. You want the readers just to get to the place where you can start to talk about code. My friend - just scradd in that command and take the rest of the day off!

npx create-next-app demo
cd demo
npx scradd . test "mocha . -R dot -w"
npm i -D mocha

I don’t expect this tool to be widely used and spread but I was pretty fun to write it - the testing was particularly tricky to get working.

Get the code or download the tool using npx scradd

Read on ...

Some thoughts on scaled agile


I indirectly got a question that I thought would make a good blog post. The question came from the brilliant Emer on this LinkedIn post. That post in itself is a great read on the US Air Force’s thoughts on agile in general - great stuff in there.

Anyhow - Emer asked me:

Yes! I have read many posts by Allen Holub and our friend Woody Zuil on this. I do struggle though to find a way to practice “true” agility at a large scale. Do you have any good resources on this?

and I started to write a response but realized that I needed some more space. This blog post is that response.

Read on ...

Run react-script tests without watch


Oh, man! I’m so happy that I’m still sane. This error was about to drive me crazy.

Here’s the back story - we have about 120 repositories with a lot of exercises and tests. This is nigh on impossible to maintain by hand, so we have written scripts to verify the integrity of each repository. Each script is verifying that installation, linting, and testing works as expected.

The whole thing is built-in bash scripts and for the most part, works just fine. It’s quite rewarding to have it checked automatically, read about it here

But the repositories that have been created with create-react-app have caused problems from day one. They work just fine when we use them normally, but in the script, it’s flaky at best and just hangs at worst.

But. Now. I’ve. Found. A. Solution.

Read on ...

Next.JS Error: No router instance found


I ran into a stupid problem I created for myself. And then I solved and that made me realize a thing about Next.JS and the server side rendering features of this framework.

I wanted to share my failures and solution to the problems I created here.

Read on ...

Uploading pictures to Firebase in React Native


It was quite some times since I wrote a programming related blog post - but now the time has come (and my programming output is poured at the Salt protips blog nowadays)

I’ve ventured a bit into React Native development and found it very enjoyable, especially in combination with Firebase stuff. But I had a really hard time finding a good example of how to upload files from my phone to the Storage services using Expo. I found this but I didn’t find it easy to follow as all of the code is in one single file.

So I took the original code and refactored it a tiny bit for better readability. My code is found here and in the post I’ll walk through some of the things that made me look twice.

Read on ...

Some questions about estimation and plannning


One of the most amazing things about my current job as a teacher and “head master” at Salt is to see amazing people take my material and make something more amazing with it. Or when see people start to venture down avenues that helped me (in this case agile, lean and no estimates) so much.

I got a question from Øyvind Ege - a brilliant developer from a class last spring/summer. And with his permission I will here publish his question and my response.

I hope you find it useful.

Read on ...

Formulation - the crucial (often missed) step of BDD


Very early in my agile journey, I stumbled over Behaviour Driven Development (in that exact blog post, in fact - Thanks Dan). And like many, I first thought of it as a more user-friendly way of writing tests.

But pretty soon (through the help of Specifcation By Example - Thanks Gojko) I realized that the true power comes from the shared understanding that stakeholders and delivery team can get from writing the specifications together, before we start, as examples/tests using concrete data.

I was hooked and Cucumber was my poison. A programming language for requirements. Executable specifications, I mean - come on! This is now 15 years ago and I still am a big fan of this way of working.

Hence I was really happy to see that two of my BDD-heroes (Gaspar and Seb) have come together (again) to write about the often neglected and missed part of BDD - how to actually formulate the scenarios.

The book is aptly named Formulation and it is packed with goodness as it goes through not only the syntax and possibilities of Gherkin (which is the way you write specifications in Cucumber) but also many examples on how the crucial collaboration can be done.

Throughout the book, we follow a few sessions with an imaginary team, which teach us good ways but also warns us about pitfalls and problems. Seb and Gaspar also sprinkle the book full of their own experiences and anecdotes, which provides good real-life applications of their advice.

What really stands out for me is the emphasis on reaching for shared understanding, with the automation of the features being a valuable side effect. This is the one thing that I see most people misunderstand and, like me, think of Cucumber as a way to write tests. Which misses out on the main benefit of this collaboration tool.

The chapter on organizing the specifications to help them support the goal of living documentation was really useful too.

I also appreciate the chapter on Legacy code and using their suggested work patterns there. No software is an island (is that a song yet?) and writing down your current understanding as business readable specifications is a really good way to strike up a conversation about what the system actually does now. You’d be surprised how often that is not known…

All in all, I would recommend this book to anyone that wants to find a better, more fun, and effective way to handle specifications. And, since I read it, you should buy the Discovery book too…

Read on ...

Christmas greeting


This year has been a very strange one, for most of us. I thought I’d share a little Christmas Greeting.

For me personally, I’ve gone through one of the big personal crisis of my life that led to a sudden, and deep, fatigue syndrome. I am better but it takes longer that than I wanted and I still am fighting a lot of different symptoms of the sickness.

But there is hope. For all of us there is hope - we can do this. We can get through the pandemic, drepression and fear. I’m sure that we will make it - and I’m sure that we will come out stronger, wiser and probably learned a lot.

Before dragging y’all down into a hole of dispair I better get those Christmas Greetings out of the way, right?

  • All lovely collegues at Salt - what a crazy year. Thanks for sharing it with me and thanks for amazing work, flexibility and success we have had during this time. And an extra big thank you for your care for me in the last months. It’s been great to feel that you care for me
  • All the students at Salt, current and past - you are all winners and amazing. It’s a joy to follow your progress and see you how develop not only as software developers but as humans too. I’m so proud of each and everyone of you
  • My friends at Aptitud, especially Anders Löwenborg - thanks for you special care for me. It means a lot of have you behind me.
  • And all people at social media that have reached out to send a greeting to me, sometimes without me knowing you in the first place. I am so grateful. I’m not in a place where I can feel the full extent of that love but I still cheerish every greeting. Thank you so much

Finally - I wish you all a very Merry Christmas and hope for a new, better, stronger and healthier 2021. All the best to you and yours. God bless you all.

I have a favorite Swedish Christmas song that talks about this hope that we will be together again, and share in joy and fellowship together. For me there’s a sentence that sums up my last 6 months:

I have paused at the road to rest for a while

That’s where I am now. Life is on pause for while. But I’ll be back and share it with you all.

Here it is, with me playing together with my good friend Jon-Anders Martinhussen - Koppången by PerErik Moreus with a lovely lyric by Py Bäckman (translation below)

There is stillness and silence, as the ground is coloured white.

From the safe, old church the song is flowing out

I have paused at the road to rest for a while

And was caught by the borderland that unites night and day

And a ray of light behind the arched window frame

Has united those spirits that are here in time with us

And I know that those who have left us have understood that we are

Like flickering flames as long as we are here

There is stillness and silence as the hymn fades out

But I carry the old words in my heart just as before

And I sing to the heavens, maybe someone else listens

“Hosianna in the highest,” then I start to walk

And I go to the others, I want to feel Cristmas peace

I want to believe that He was born and exists with us in time

It is Christmas and there is a child in me that wants to think that it happened,

And that lights a candle every Advent Sunday

Read on ...

Marcus and the wall


The thing that I’ve feared but never thought would happen has come to me to.

I have come down with the fatigue syndrome and a depression to follow. This is something that has been building up over many years and bursted out fully after the spring that was very though on me.

It’s now in its fifth week and I’m going to take some kind of program at a clinic that is geared only to handle this type of problems.

I’ve gone mostly of grid. First three weeks was just me crying and sleeping, so I was not much use to anyone anyway. I’ll be keeping it like that (off-grid) for the foreseeable future until I know what I manage.

Lots of confusing feelings right now where I’ve lost all my confidence and self worth while at the same time feel very tired. Right now a single telephone call is enough for me to need a nap, I sleep at least twice a day and then throughout the night, I’m sad and can’t see my future… In short - I’m not feeling well.

I just wanted anyone who wonders to know about my state.

I will get out of this too. Right now I don’t know how, but I’m hopeful it will happen.

Now this blog will be quiet for a long time.

Bye

Read on ...

Role Models - Lars Littorin - the senior consultant


I’ve started a little series of some (by far not all) of the people that have shaped me during my career as a consultant. The more I think back of the things they said, did, and taught me - the more I can see how I’m using their advice just about every week.

Today the turn has come to a colleague that I had at Cap Gemini - the first senior consultant that I worked with and someone that made a huge impact on me and my ways; Lars Littorin

Read on ...

Role models - Christian the developer


I’ve just started a series about a few a the people that have shaped, influenced, and affected me throughout my career. The reason I’m writing about this now is that I lately have had the opportunity to be a role model for other young developers - I notice that much of what I say and do comes from others; things I’m saying, manners I’ve picked up, approaches to code, development, and life in general.

I am, as the saying goes, standing on the shoulders of giants. For what they have done for me I’m very grateful and I wanted to show that gratitude here.

The first post was about Staffan - that showed me servant leadership and what a consultant is. Today it’s about Christian Forsberg, a rock ‘n roll developer.

Read on ...

Role models - Staffan the consultant


I have a great job! I get to work with a lot of young people and get to train developers in the early stages of their careers. It’s absolutely amazing to see people develop in these early steps of their career.

But it also creates a weird feeling for me - since I, to them, comes out like an old sage telling stories that are long-forgotten about how the web was when the world was forged. Back in 1996 and stuff. I feel both a bit like Gandalf - both in age, length, and how I’m addressed.

Gandalf

It’s scary. Because, if we’re going to be a bit more serious, I realize that I become a role model for some of them. How to behave, act, say, and think about our work. This is especially real when we talk about agile practices and techniques, that has a lot of principles and thinking patterns in them.

This made me think about my own early influencers in this industry. And I realized that I never said thank you to them. And that many of them probably have no idea what working with them meant to me.

So, this is the first post in a series of “thank you”-notes to my early role models. Today it’s Staffan Rolfsson - one of the first.

Read on ...

Bash scripting to check the status of 100 repositories


At </salt> we have a lot of labs and tests. Last time I counted we just passed 100 repositories. And it’s dawned on me that all of those need some love and attention from time to time. Stuff moves pretty fast in the JavaScript world and dependencies might start to act up etc.

At least you’d want to check out the code, do an installation of dependencies and then run the test and see that you get the expected behavior. Preferably you’d also wanna see that we don’t have deprecated dependencies or broken stuff. And probably check this, at least once before each course.

This is what scripts are made for, right? Automate the boring stuff.

The only problem is that since we are teaching a lot of different technologies and tools, not two repositories are the same; this one uses Docker and this is actually just text, and over here we have one that is purely for CSS-stuff. In one repository we should have 4 failing tests but no linting errors. In the other, we need 42 liting errors but no failing tests. Etc, etc, etc. It’s nigh on impossible to write a script that checks this for me. It’s pretty much custom code and checks in every repository.

This problem pushed me to investigate how we could automate this process with bash scripts. I learned a lot and wanted to share a bit.

Read on ...

Building teams - where our training starts


At School of Applied Technology, our accelerated career program is running in small teams, using Mob Programming. We have found that this gives us the most and best learning in a short amount of time. In this setup the tight group that you are in becomes both your best teachers but also, from time to time, you will be the teacher others in the group.

Read on ...