Django Test Mock Factory

There are many ways to use Python Mock’s patcher, but sometimes there’s something in your test module you’ll always need to mock. It’s possible to apply the patcher to the entire class, but it still means you have to litter your tests with parameters. To make things a bit tidier and DRYer, I started using the following mock factory in my tests to create instance-level mocks.

def add_mock(self, target, *args, **kwargs):
    target_obj = target.split('.')[-1]
    patcher = patch(target, *args, **kwargs)
    if target_obj[0].isupper():
        # Assume class mock
        attr = 'Mock'
        attr = 'mock_'

    attr += target_obj

    setattr(self, attr, patcher.start())

The above attribute factory will add new instance level attributes, named either mock_some_variable for imports that look like variables or functions, or MockSomeObject for imports that look like objects. It will use the patcher’s patch function directly, and assign the new attribute to the current test object instance, then stop the patch at clean up.

This can be used in your tests’ setup method like so.

def setUp(self):
    module = ''
    self.add_mock('%s.settings' % module)

    # Pass patch arguments through the setup method
    self.add_mock('%s.send_mail' % module, autospec=True)

    # We now have an instance-level mock to work with
    self.mock_settings.REPORT_TEMPLATE = 'test-template'

Now all your test methods have instance attributes to work with instead of a long line of parameters. Much better!

def test_the_first(self):
Development Web

Regex to find CSS Class Uses

I needed this to find uses of a specific CSS class in order to replace them all with a namespaced version.

class=(["a-z\-]*[" ]+)(nav)([ "])

Optionally use the replacement text below, complete with variable markers. In this case, “nav” will be prefixed with “forum-“.


My Time With Act 1 of Broken Age

I finally had a chance to crack into Broken Age and sample its particular flavor of adventure-game-goodness, and have had some distance on that experience that I felt like writing a little something about it. I think the last point-and-click adventure game I played was probably Telltale’s Back to the Future, unless you count The Walking Dead, which I feel like was an altogether different kind of experience. There have certainly been a great deal of indie point-and-click offerings lately, but they haven’t drawn me in like the days of Full Throttle or Grim Fandango, and even the games I mentioned playing recently didn’t leave a huge impression on me. There’s a unique whimsy that exudes from Tim Schafer’s games, and it’s his ability to craft a believable, yet bonkers world that feels grounded in its own rules, that keeps me coming back.

Broken Age is a story about childhood defiance, and the themes of child-parent relationships feel as though they come from a place of experience. Parents want to keep their kids safe, but also want them to flourish in a world that is unsafe. Without talking too specifically about the story, Broken Age does a decent job of exploring both sides of this relationship to its extreme conclusion. The game is full of interesting characters that are well voice acted, and for the most part serve as conduits for some thoughtfully comedic writing. Only a couple of characters spring to mind that fell flat – one of which seemed to serve as more of an outlet for Bay Area stereotypes – but that’s a good ratio when the game has such a broad cast, even in just this first act.

The story is brought to life through a beautiful hand-drawn art style that looks straight out of a modern children’s story book. However, the writing has that Pixar quality of reserving a wink and a nudge for adults, while remaining still something that could be enjoyed by a younger audience. Indeed, the art style is so strong here, that I wonder where else games could have gone if they continued down the 2D path instead of moving to 3D in the 90s. With the funding and budget for this game being so public, it seems like it was absolutely the right move to make this game in a 2D engine; I’m not sure this level of visual fidelity could have been achieved otherwise.

As a person who played many point-and-click adventure games in the 90s, my view on the puzzle difficulty is probably skewed, but I didn’t find the game to be all that difficult. Any time I didn’t immediately know the solution to a puzzle, I simply needed to go through all the dialogue options with another character, and the solution would reveal itself. The gameplay consists of what you’d expect from the genre, the loop of talk to characters, find items, use items to solve puzzles, is all present and accounted for here. There are some interface nuances that feel like they were designed for touch devices. By default, items are used by dragging them, and there is an ever present inventory pop up in the lower left of the screen which occasionally interfered with navigation, but much of this behavior can be changed in the options. It’s an adventure game through and through, so all backers can rest easy that Double Fine delivered on that front.

The first act of Broken Age felt complete, with its own fascinating arc, but ends with an unexpected twist that left more questions than answers. Throughout the game there’s a sense that something is amiss, and the way this act wraps-up plays on that feeling masterfully. It probably goes without saying that I am highly anticipating the next installment, and if Double Fine can keep up the quality, there’s a good chance this will be one of my all-time favorite adventure games.


Diablo III After the Auction House

It’s a real sign of the times that a large company like Blizzard can react to feedback on the controversial Auction House feature in Diablo III, and ostensibly compromise the original vision of the game and its business model going forward. It certainly seemed like the kind of thing that was here to stay, given that it resolved the grey-market sale of in-game goods, and gave Blizzard a cut as well, so it’s worth applauding the wardens of the series for pushing to simply make the actual playing of the game that much better.

I should mention that I didn’t play the original Diablo, or Diablo II, but I have played other similar games, such as Torchlight, enough that I feel like I know something about the legacy of those games. I played Diablo III around launch and had a pretty good time with it, starting the game with several of the available classes before settling on the Wizard and playing through the content about 1 and a half times. I can’t say I felt too much like the loot in Diablo III wasn’t good enough often enough, or that the scaling of loot felt unbalanced – I was keeping up with the difficulty of the content, and that’s what mattered. However, I would say that the very existence of the Auction House changed my thinking about loot I wasn’t going to use for myself. This meant knowing what was important to all classes – what stats to look out for on item drops – and holding onto those items; after all, I wouldn’t be taking advantage of a major feature of the game if I didn’t. As you might expect, this made the process of loot sorting that much more tedious, because none of the comparison features in place were there to help you decide what’s good for other classes. The fun was sapped out of the game, and it became more and more about the money. I’m sure that aspect was fun for some, but it fundamentally changed how I played the game in a way that would eventually lead to something resembling workflow optimization. Gross.

I’m happy to say that with the advent of Blizzard’s “Loot 2.0,” the game has returned to feeling like a game. The first few hours of time with this update were filled with finding loot that was so much better than what I had, it felt like some big apology, and now that the Auction House is removed, if I find anything that’s not better, it gets immediately trashed. It is as though I am the center of my Diablo experience again, never sparing a thought for the real-world ramifications of that axe I found, or this Crossbow of the Bear’s Lamenting Tide – it’s all about what I need so I can get to slaying more demons, and in the end, isn’t that all any of us wants?


First Person Camera Lens

I was recently having a discussion with a friend who found the visual effects applied to the camera in many games to be incongruous with his idea of seeing through one’s eyes, especially in first person games. The idea of treating the view into the game world as a camera seems logical enough, and lens effects had humble beginnings, like the lens flair that featured prominently in games from the late 90s. However, developers have been pushing these effects to even greater extremes lately, with High Dynamic Range (HDR) lighting simulating more how a camera would react to differences in light than the human eye, and heavy lens dust effects in Battlefield 3 and ZombiU. Such effects reduce the visual fidelity of the information available to players, yes, but provide a more cinematic visual experience. This is the argument you would probably hear in favor of lavishing more image-reducing effects onto the screen. However, it still doesn’t address the issue of dissonance when this is supposed to be a person’s eyes.

It occurred to me, while discussing how this all came to be, there are probably a couple of subtle factors at play here: Making games look good is a marketing tool, and the closest mediums that most people would understand are film and photo. Take your screenshots and trailers, make them look as close to professional photos and cinema as possible, and most people will think that game looks impressive and worth investigating further. I believe this type of thinking overtook the idea of representing the world cleanly in first-person, but was also influenced by the fact that first-person games were not as common when camera lens effects were really becoming a thing. It felt relatively natural, when the most popular genre was racing games, that the camera should act like a camera (save for the odd first-person camera, which wasn’t really the focus on consoles). I believe that thinking just eventually became pervasive, since it’s so easy to always think of the view into the world as a camera.

It seems then that these camera lens effects simply had to be applied to every type of game that purported to be even remotely realistic – a real irony when reality, as seen through the eyes, features none of these things.


Bioshock Infinite Themes and Social Reflection

I’m going to write pretty explicitly about some things in Bioshock Infinite for a moment, so consider yourself spoiler warned!

Much discussion has been made of the story in Bioshock Infinite, and it’s certainly a big part of why I love the game, but it’s the themes around the world of Columbia that caused me to think most on the experience after finishing the game. To be clear, I’m aware the game isn’t really about Columbia, but I still think it’s an interesting topic of discussion.

The society of Columbia draws many parallels with Rapture from the first Bioshock, but of course, it is clearly not an objectivist society. For one thing, it is mentioned that the people of Columbia pay huge tithes to the Prophet, and there appears to be a public service in place. However, while Columbia’s citizens didn’t fall into a spiral of abusing vigors, they did find themselves facing the same issues regarding the workforce. After all, nobody wants to do the dirty work, and if they do, they expect to be highly compensated for it. The solution in Columbia was to introduce an already downtrodden underclass, and keep them feeling helpless, but with enough of a promise of a better life that they’d want to come in the first place. It’s easy to look at all of this and say “yes, I know, racism is bad; sweatshop labor is bad,” but we can only say that with the perspective that being in another time grants us. At one time those things were considered the norm–that’s just how things were. How much, then, do we accept as the norm, now, that will be considered barbaric in 50 years time? How about 100 years time?

The way in which we work, or are expected to work, might be drawn into focus in the coming years. Workers might not be treated as badly now as they were at the turn of the century, we might disallow child labor, but I think there are much subtler issues still lining the way we treat work, and its relationship to our lives. Take, for example, the general trend of declining birth rate in economies that become better educated and are more innovation and intellectual property producing. Whether this is to be taken as negative is another matter–I’m interested in why this might be. It seems plausible that a better educated populace better knows the implications and responsibilities, both financially and otherwise, of having children, but also that career competition kills the desire to have children; if one is to remain competitive, flexible, and appear enthusiastic in the workplace, then there is little else one can do but to have few, if any ties to one’s personal and family life. Occasionally with age and experience, professional stock increases to a point where workplace flexibility may be demanded, but it’s not always the case. Indeed, the ruse of workplace flexibility might be easily shattered with the sentiment that if someone else is willing to work longer, for less pay, and do roughly an equivalent job, then why wouldn’t they be chosen? Something always suffers, a sacrifice is always made, between work, family, and life–something we’ve come to call work-life balance.

There are those who genuinely have a choice. At one time called aristocracy, at another called the 1%, but the constant is that it remains a small slice of society for whom survival plays no part in their decisions over work-life balance. It is through this that it becomes apparent survival is key to understanding the relationship to work for the majority of the populace, it is the means of continuing to live at one’s current living level. However, because of the emphasis on balancing a life toward work, we may well be sacrificing so much else of ourselves in the process. The subtle forces at work that make this the status-quo mean that it becomes perfectly acceptable for a parent to boast that they spend a “solid hour” with their child in the evening, while another demonstrates how dedicated they are by lamenting that they hardly even know their children. Furthermore, not every pursuit is productive in a way that is demanded by the market, but is no less good for the mind and body, or the collective culture; in many cases they are better. Would it be so bad for a parent to just be a parent? What a bout a 4 hour work day? Parkinson’s law might suggest that if we were only given 4 hours a day to get everything done, we’d probably still manage it. For now, though, presence remains the the most valuable aspect of an employee, and this will probably remain without increased social awareness.

I like to think we will see some improvement in these areas, and there has certainly been a sense of ground-swell, but for now I can only look forward to new thinking and hope it encourages others to consider another possibility, too.


Evolutionary Diet

Our problem with eating a healthy diet typically stems from not ever needing to evolve the ability to know when to stop eating the things that appeal to out tastes the most. Sugar and fat are probably highest on the list of things that are bad for our health in large quantities, so why do they taste so darned good? As our tastes evolved over millennia, those were the most scarce of foods. However, now that we have the ability to manipulate the world around us, our tastes and digestive systems haven’t caught up–we still crave fats and sugars, except we’re not programmed to stop eating them when we probably should.

While watching a show about an attempt to overcome the desire for sugar in almost everything, it occurred to me that there are almost no natural examples of fat and sugar in the same food. An orange has sugars, but no fat, while an avocado has fat, but no sugars. The only naturally occurring example I can think of is milk, which makes some sense, given its role as nutrition for infants. Given this, and the earlier observation that our digestive systems were designed around whatever was available in the natural world, would it not therefore make sense to devise a diet that allowed for all foods, but not high-fat and high-sugar foods in the same meal? Granted, this would probably eliminate almost all deserts, but maybe that’s evidential in itself.

Who knows, it could end up becoming the next Hay Diet!


Giant Bomb Video Commander

I recently wrote a Chrome Extension, partially because I wanted to learn how one can be used to inject functionality into an existing website, and partially because I really wanted some functionality that wasn’t already on Giant Bomb. From this was born the Giant Bomb Video Commander! It’s a simple extension that injects some Javascript when there’s a video present, and adds keyboard controls for HTML5 video objects.

I’ve posted a GitHub repository of the source as well.


Business Objects: Room Occupancy

Sometimes Business Objects can make the simplest thing super difficult—if you’re used to using SQL. In this particular case, I just needed an outer join in which I can count the number of rows that have something on the left of the join, and those that don’t.


We have data about rooms in a hotel, and we have data about bookings. Bookings are associated to a room by the room ID, and they have a begin and end date, so we know who is in what room at any given time. We have a data cube in which all rooms are shown with booking details if there’s a booking, and a blank space if there isn’t. We want to show a count of occupied and unoccupied rooms off to the side with a single dimension and single measure, so we can do some nice charting.


We need a variable that shows whether a room is occupied or vacant. This can be achieved simply enough with a dimension that has the following code.

=If IsNull([Booking ID]) Then "Vacant" Else "Occupied"

If you put this next to your list of rooms and bookings, it should show when a room is occupied or vacant. That’s not very interesting by itself, so let’s  start counting how many there are.

You can create multiple measures counting all rooms, occupied rooms, then available rooms by subtracting one from the other, but this leaves you with multiple measures and isn’t suitable for certain charts.

To have a block with the two possible dimensions counted, I started with the following.

=Count([All Rooms].[Room ID])

Create a block that has the room occupancy variable dimension and the count. Make sure it is also set to Show rows with empty dimension values, and what do you get? A count of one for both? Yeah, I had that problem too.


It isn’t enough just to count, you have to count without row aggregation. That means we need to count every row in which “Occupied” or “Vacant” occurs, even if they are the same (which is kind of the point).

The mistake I made was in the counting variable, so let’s fix that.

=Count([All Rooms].[Room ID]; All)

That little “All” as the second argument makes all the difference! Ugh…

You should now see a count of all room states as expected, and can now make fancy charts all you like.


One thing to watch out for is if you are actually getting some duplicate rows for another reason, you’ll be counting those, too.


CakePHP ACL and Groups

There are many great tutorials out there to help you get started with the arcane ACL features of CakePHP, but none of them seemed to cover a specific problem that occurs with reassignment of a parent_id on a save operation.

The parent_id would revert to being null on some save operations on the User model, so if, for example, the user changed their password, they’d end up with no group and an infinite redirect; the redirect loop occurring because everyone should be in a group. Upon investigation with a debugger on task, I discovered the problem resides with the parentNode function, and that all other examples out there are written with the expectation that a group_id will be present in every save operation.

Since parentNode is always called on a save operation performed on a model acting as an ARO, some modification of the typical example is necessary to ensure that you’ll always have the group_id available for finding the parent node ID.

function parentNode() {
  if (!$this->id && empty($this->data)) {
    return null;
  $data = $this->data;
  if (empty($this->data)) {
    $data = $this->read();
  if (empty($data['User']['group_id'])) {
    $groupId = $this->field('group_id', array(
      'id' => $this->id,
    if (empty($groupId)) {
      return null;
    } else {
      $node = array('model' => 'Group', 'foreign_key' => $groupId);
  } else {
    $node = array('model' => 'Group', 'foreign_key' => $data['User']['group_id']);
  return $node;

Like in the Change Password example, on pages where user data is changed, but the group_id is not needed, the parent_id can now be found for the User ARO. On the other hand, you won’t overwrite the group_id if the data indicated it should be changed.

Hope people find this useful, and if you have any suggestions for improvements, let me know!