Friday 17 May 2024

Recommended Pattern for Shared State in GoDog

Clarity, Concurrency, Convenience

I'm currently making some changes to Cucumber godog which is a behaviour driven development tool for golang. Whilst writing some tests I've strrugled to find a nice pattern for shared state across steps.

What is the recommendation when we have a collection of values that we need to share between steps?

A common anti-pattern I've seen in godog usage is just to have a bunch of global variables. This approach has at least one shortcoming in that this pattern doesn't lend itself to parallel execution because global vars would be shared across all threads and so the threads would trample on each other.

Godog, like Cucumber JVM, does provide a better method to share state across just the steps in a single scenario and this approach isn't succeptible to the issues that globals would. You can see examples of this proposal in the godog documentation where "context.Context" is threaded through the steps and and necessary shared state is comunicated by adding it to the context.

However, the godog docs don't provide evolved examples of the practices around the use of the context and only show storing a single primitive value into the context. 

But, what do I do when I have a collection of state values that I want to share?   

My preferred solution to this is to create a struct that encapsulates all these shared values and which can be added to the context. This is somewhat similar to what we always to in Cucumber JVM.

I then provide a utility function to access the shared state. The pattern I illustrate below is the most convenient I've come up with. This pattern is also convenient in that we can easily trace where the various shared state fields are accessed. 


// Struct to encapsulate the shared state into ordinary typed fields
type SharedState struct {
    Name string
    Url  http.Url
}

// key used to store/retrieve the shared state from the context
var shareStateKey = SharedState{}

// utility function to retreive the state object from the context.
// this utility adds the state object to the context if it's not already present.
// because we're returning a reference to the shared state then this is effectively
// a mutable object, which leads to convenient syntax in the steps below.
func getSharedState(ctx context.Context) (context.Context, *SharedState) {
    v := ctx.Value(shareStateKey)
    if v == nil {
// if shared state wasn't found then create it and update the ctx
        v = &SharedState{
            // empty
        }
        ctx = context.WithValue(ctx, shareStateKey, v)
    }
    return ctx, v.(*SharedState)
}

// example of usage
func someStepDef(ctx context.Context, stepArg string) (context.Context, error) {
    ctx, state := getSharedState(ctx)
    state.Name = stepArg // read/mutate the shared state
    return ctx, nil // we must always return the ctx on all code paths
}

// another example of usage
func someOtherStep(ctx context.Context) (context.Context, error) {
    ctx, state := getSharedState(ctx)
    fmt.Println(state.Name) // read/mutate the shared state
    return ctx, nil // we must always return the ctx on all code paths
}

  

Saturday 20 March 2021

Hardware Hacking

Since the last post here I've taken to a bit of further hardware hacking and most of this is recorded on Hackaday  https://hackaday.io/johnlon

The CPU project I started in 2019 is called SPAM-1 and is still underway but it's taken on a bit of a life of it's own. More info on that can be found in it's github repo https://github.com/Johnlon/spam-1

Monday 15 April 2019

Kennedy Space Centre: In a day

Visited Saturday April 13th 2019

The following timeline was what I achieved as a lone adult visiting KSC for the first time.
I think if my 14 year old's were with me then I'd probably have gone a bit slower due to spending more time looking at various exhibits.

Apparently this was not a busy day despite being a Saturday 2 weeks before Easter.
I was told that a lot of folk had come 2 days earlier to see the SpaceX heavy launch.

----

Book tickets ahead of time - I booked a week ahead.
- entry ticket
- parking
- book the extra 10am extended KSC Explore Tour or the Early Space tour according to interests - of course the free tour is shorter but it doesn't include stop offs at important locations

But ...
- do NOT book the audio guide option - just not worth it (I tried it and it's not necessary).

Print off every thing.
By the way the tickets look completely different when viewed on
a PC versus on a phone and they will print differently too.
You MUST bring printed copies with you - print them on a PC.

For the extra tour you need to go to the information office at the gate.
They will give you a badge.
BUT do not give them the paper printed copy of the bus ticket that you brought with you, as this will be asked for at the bus stop later on.

Top tip: Apparently there can be long queues (1 hr +) for the free bus tour.
However, the extra paid tours have no queues as you pay for specific bus times.
This fact and also the extra sights and stops makes the paid tours essential in my opinion.

---

I got there 8am.
Car park opened at 830 and I parked right by turnstiles.
Turnstiles opened 9am.

At 8:30 I went immediately to the information office to pickup the ticket for the extra bus tour I'd booked Just put that ticket away somewhere safe and also DO not give them your printed voucher as you may be asked for it at the bus stop as I was.

---

After the 9 am entry I went straight to "Hero's" 3d display up the ramp to the left just inside gate, before going to the rocket garden.
At the hero's exhibit is an irritating but short 6 min "what does it mean to be a hero" presentation, but this is followed by a much more impressive but also short 3d presentation in a surround screen.

When you enter the second theatre stand right at front in the middle of the lower tier middle with the screen surrounding you.

Exited exhibit around 9:20am so I was only in there for 20min.
The guide says this takes 45 mins but I didn't spend any time reading the individual information on the astronauts mentioned in that building as I had to move on quickly for the rocket garden and bus.

--

Waited at the rocket garden for the 9:30 guided tour to start.
Do this tour.

Rocket garden tour finished at 9:45 and left plenty of time to walk the 2 mins to bus stop for the 10am bus tour I'd booked.

--

At the bus stop give it 5 mins to sort out passes by the bus - you will need to hand over the paper bus tour voucher that you printed out for yourself (at least I was). I don't know why they wanted the print out given I'd already obtained a clip on ticket at the information desk before entering the gates.

Also buy water from the vending machine at the bus stop.

I took the 10am extended "KSC Explore" Tour. The 10am bus actually left at 10:15,

This extended tour does everything free basic tour does but is longer and has more stop offs.
It has a human guide, and you can get off at three additional spots whereas the basic tour stops at one. The "Explore tour" takes you to three view points around the site, the first one is a place with chairs for viewing launches, the second stop is place closer to launch pad 39B where one can take photos of the Apollo launch pad from a distance; there is also a drive by of 39A. The bus then includes a good stop at the vehicle assembly building (VAB) where one can get great photos of the VAB and also see a gantry for the shuttle and also some escape vehicles.

BTW On the internet you might see advice about sitting on the right of the bus.
Sitting on right of the bus gives the best best views from bus of the vehicle assembly building (VAB) and also of the tractors that were used to pull the Saturn 5 and Shuttle to the pad.
However, given that this extended tour allows you to get off at the VAB then the seating location probably isn't as important as it is on the basic free tour. In fact there were some better left side photo opportunities from the bus when we were approaching the launch pads 39 A and B; but even then the drive slowed down to give folk a chance to look and photo.

We left the VAB at 11:48 and arrived at the Saturn V building around 10 mins later.

---

On arrival in the Saturn V building around midday I had a good walk around the rocket.

I watched the "Apollo 8 firing room" presentation in the Saturn V building - the theatre is at left of rockets nose. https://www.kennedyspacecenter.com/explore-attractions/race-to-the-moon/apollo-8-and-the-firing-room

Also see the "Race to the moon" presentation in the "Lunar Theatre" at the Saturn V building.
https://www.kennedyspacecenter.com/explore-attractions/race-to-the-moon/lunar-theater

If I recall correctly the "Race to the Moon" exhibit is directly after the "firing room" exhibit.

Touch moon rock - on the left of the Saturn five space, about half way down, there is a smallish exhibit cabinet where you can slide your hand into a slot and reach in to touch a triangular sliver of moon rock. 

After that , I ate lunch in the Saturn 5 building. I bought some nasty spicy chicken thing, but they also had better looking salads and sandwiches.

I then had a final look around the Saturn V building and took a return bus to the main centre at about 1:25pm.

---

I then wandered over to the Atlantis exhibition building.
There is a winding ramp inside the main entrance to the building that takes one up to a theatre for a short 15 min presentation and then entry to the "hanger" containing Atlantis, exhibits and also the "shuttle launch simulator" ride..

On the day I was there there was a short queue inside the building on the winding ramp - It only took about 15 mins to get into the theatre.  However, I can imagine this queue is longer on busy days.
Top tip: If there is a big queue on the ramp into the Atlantis exhibition theatre then abandon the theatre and instead enter the building via the gift shop outside to the right of the main entrance.
You'll miss a 15 min video that's all.

Either way spend some time viewing the shuttle. On the day I was there there was an astronaut casually talking to folk.There is a slide from upstairs to downstairs the kids liked.

On the ground floor there is a "Shuttle Launch Experience" simulator. This is definitely worth doing. I actually felt like the skin on my face was being pushed back.
I started queuing for launch sim at 2:10pm and was back outside the Shuttle building by 2:45pm.

---

After that I did a quick walk through the Mars rover exhibition building.
Then I left and wandered for a few mins.

---

Before 4 pm go to the theatre where the astronaut of the day is doing their presentation.
Go there some time BEFORE 4pm as I got there at 4 and wasn't allowed in..

I wasn't that bothered as I'd met and chatted with Al Worden in London a couple of years before.

---

So I was finished around 4pm and was pretty tired.
I had to get to airport to fly back to London that evening anyway so really didn't have much spare time.

I left abut 4:30pm after resting for a while by the gate where there is a covered area with wifi.

---

It was closing at 6 or 7pm that night so I had time for other things perhaps but I'm not sure how these would have fitted in.

I missed the Hubble exhibit - didn't even know it was there.

----

This was definitely a great day and if I'm back here with my family I will come again.

Have fun.

---

I've included some more thoughts on the bus tours below - I'm not certain about everything but it might be useful to you.

There is a free bus tour included but it stops only at the Saturn V building, whereas the two pay-extra tours go further afield and include multiple stop offs..

I did this one:  https://www.kennedyspacecenter.com/explore-attractions/behind-the-gates/kennedy-space-center-explore-tour  "See icons of spaceflight operations like the Vehicle Assembly Building, historic Launch Complex 39 and disembark to capture once-in-a-lifetime photo opportunities."

But there is also this one:  https://www.kennedyspacecenter.com/explore-attractions/behind-the-gates/cape-canaveral-early-space-tour  "Tour stops also include the Air Force Space & Missile Museum, the Mercury 7 Monument, and Launch Complex 34, the memorial site for the crew of Apollo 1."

The tour I did was about 2 hrs. 
I think the early space tour is the longest one 3 hrs.
The one I took "Explore Tour" was 2hrs and I hadn't realised that it actually stopped at the VAB, but it also had photo opportunities for launch pads 39 A & B which were used for Apollo, Shuttle and now SpaceX. I don't know if the "Early Space" tour includes these locations, but the "Early Space" tour definitely goes places that the "Explore Tour" doesn't. 

I understand that either of these alternative tours include all the sights of the free tour, but the free tour only does a drive by of the VAB.

It might be the case that the longer "Early Space" does everything that the other two tours do plus extra things - I have no idea.

To be sure one could phone or email them.

I don't think one could easily do both of the extra tours in a single day and also see the other stuff. It might be possible but it would be tight. Also, KSC advise against trying this.

Anyway hope that's useful and have fun.

Monday 21 May 2018

Accessing guest webservice in hosted vm

Wasted hours on this.
If having set up port forwarding or bridged you still can't connect to the guest's web server then possibly the guest firewall is blocking it.
For instance I was able to SSH to the guest OS instance but not connect to port 8000 where my guest was running a web service.
Using 'curl -v' I was able see that curl was making a connection and sending headers but getting no response.
So in my guest, which was centos, I put in a set of rules to effectively disable it iptables.
That fixed it!
---

Do in this in iptables has temporary effect until reboot...
   sudo su -
Then..
  iptables -P INPUT ACCEPT
  iptables -P OUTPUT ACCEPT
  iptables -P FORWARD ACCEPT
  iptables -F
Then try hitting the  address from the host again.


To make the changes permanent on Centos it's firewalld that I need to interact with as the front end of the firewall. This worked for me ...

   firewall-cmd --zone=home --add-port=8000/tcp --permanent

---
Other details...
My guest web service was running on centos and listening on 0.0.0.0:8000, ie all interfaces on port 8000. My host was Windows 10.
I had success with the following..
A) I setup NAT forwarding of port 8888 on my host in virtualbox to port 8000 of the guest. In virtualbox I did not provide an ipaddress for either the host or guest in the nat forwarding config. I then hit 127.0.0.1:8888 in the host and was able to access my site.
B) I also tried turning on bridged in virtual box then, after restarting the guest, I ran ifconfig  and found the network interface that was assigned a dhcp address by my router. This address was one starting with 192.168.0. as that's how my router is setup. Mine was 192.168.0.62 but yours will be different.
I then hit 192.168.0.62:8000 and was able to contact my site.
C) Finally I setup a bridged network in VMware workstation Player and did the same steps as B and that also worked.
In VMware player I couldn't see a place to configure the port forwarding so didn't try that. Probably need the paid version for that feature??

---

Friday 11 November 2016

More on the sad state of checked exceptions


Following on from my previous post about Java Lambdas and checked exceptions I did a bit more research.

I found a revealing analysis of what github programmers do when exception handling. 
As far as I am concerned it goes to demonstrate the failure of Java’s attitude to checked exceptions.


This is well worth a read; it would seem that most developers do not respect checked exceptions at all, typically ignoring them entirely or doing nothing more than logging and swallowing.

Take a look at figures 7 and 8 of the report. Clearly a lot of catch blocks are entirely empty, however what about the ones that do a bit of printing/logging? They looked closer and found that typically when either logging/printing take place then these are typically the only operations done in the catch; so only a tiny bit better than an empty catch block.

It is hard to believe that in the vast majority of cases it is really acceptable for a program to carry on without taking any action – however that’s what we see across github. 

Quality software!

Sad state of Java Lambdas and Checked Exceptions

Was looking into Java 8's functional programming features.

I instantly came across a problem that functional programming in Java 8 is incompatible with checked exceptions. Given Java’s obsession with checked exceptions this seems bizarre.

Evidence of this is found in the Java 8 UncheckedIOException class – if you look where/how this is used in the JDK it’s clear Oracle have hacked this into place to allow them to add functional stuff to their IO libraries.


It would seem that if Java programmers are going functional then they are also saying checked exceptions are effectively deprecated.

I'm no fan of checked exceptions but it would seem that Brian Goetz was aware of this in 2010 and despite that we're still in this situation. Perhaps it's the end of the road for checked exceptions?


Recommended Pattern for Shared State in GoDog

Clarity, Concurrency, Convenience I'm currently making some changes to  Cucumber godog  which is a behaviour driven development tool for...