The Anatomy of Good Unit Testing

I think of unit tests as an extension to my code. A thorough testing process offers peace of mind that when refactoring the code or making performance improvements, the units still function as expected. It can also find bugs and edge cases and avoid regressions during refactoring.

I come from a.NET / C# background and have compiled this collection of thoughts and tidbits that I find useful when writing tests.

How Do You Do max-font-size in CSS?

CSS doesn't have max-font-size, so if we need something that does something along those lines, we have to get tricky.

Why would you need it at all? Well, font-size itself can be set in dynamic ways. For example, font-size: 10vw;. That's using "viewport units" to size the type, which will get larger and smaller with the size of the browser window. If we had max-font-size, we could limit how big it gets (similarly the other direction with min-font-size).

One solution is to use a media query at a certain screen size breakpoint that sets the font size in a non-relative unit.

body {
  font-size: 3vw;
}
@media screen and (min-width: 1600px) {
  body {
     font-size: 30px;
  }
}

There is a concept dubbed CSS locks that gets fancier here, slowly scaling a value between a minimum and maximum. We've covered that. It can be like...

body {
  font-size: 16px;
}
@media screen and (min-width: 320px) {
  body {
    font-size: calc(16px + 6 * ((100vw - 320px) / 680));
  }
}
@media screen and (min-width: 1000px) {
  body {
    font-size: 22px;
  }
}

We've also covered how it's gotten (or will get) a lot simpler.

There is a max() function in CSS, so our example above becomes a one-liner:

font-size: max(30vw, 30px);

Or double it up with a min and max:

font-size: min(max(16px, 4vw), 22px);

Which is identical to:

font-size: clamp(16px, 4vw, 22px);

Browser compatibility for these functions is pretty sparse as I'm writing this, but Chrome currently has it. It will get there, but look at the first option in this article if you need it right now.

Now that we have these functions, it seems unlikely to me we'll ever get min-font-size and max-font-size in CSS, since the functions are almost more clear as-is.

The post How Do You Do max-font-size in CSS? appeared first on CSS-Tricks.

Resizing Values in Steps in CSS

There actually is a steps() function in CSS, but it's only used for animation. You can't, for example, tell an element it's allowed to grow in height but only in steps of 10px. Maybe someday? I dunno. There would have to be some pretty clear use cases that something like background-repeat: space || round; doesn't already handle.

Another way to handle steps would be sequential media queries.

@media (max-width: 1500px) { body { font-size: 30px; }}
@media (max-width: 1400px) { body { font-size: 28px; }}
@media (max-width: 1300px) { body { font-size: 26px; }}
@media (max-width: 1200px) { body { font-size: 24px; }}
@media (max-width: 1000px) { body { font-size: 22px; }}
@media (max-width: 900px) { body { font-size: 20px; }}
@media (max-width: 800px) { body { font-size: 18px; }}
@media (max-width: 700px) { body { font-size: 16px; }}
@media (max-width: 600px) { body { font-size: 14px; }}
@media (max-width: 500px) { body { font-size: 12px; }}
@media (max-width: 400px) { body { font-size: 10px; }}
@media (max-width: 300px) { body { font-size: 8px; }}

That's just weird, and you'd probably want to use fluid typography, but the point here is resizing in steps and not just fluidity.

I came across another way to handle steps in a StackOverflow answer from John Henkel a while ago. (I was informed Star Simpson also called it out.) It's a ridiculous hack and you should never use it. But it's a CSS trick so I'm contractually obliged to share it.

The calc function uses double precision float. Therefore it exhibits a step function near 1e18... This will snap to values 0px, 1024px, 2048px, etc.

calc(6e18px + 100vw - 6e18px);

That's pretty wacky. It's a weird "implementation detail" that hasn't been specced, so you'll only see it in Chrome and Safari.

You can fiddle with that calculation and apply the value to whatever you want. Here's me tuning it down quite a bit and applying it to font-size instead.

Try resizing that to see the stepping behavior (in Chrome or Safari).

The post Resizing Values in Steps in CSS appeared first on CSS-Tricks.

253: Copy

Show Description

Klare and Marie are talking copy — marketing copy, documentation copy, micro-copy, and all the other kinds of copy that you might have on an app like CodePen.

Time Jumps

  • 00:41 Redesign of the Pen settings panel
  • 07:08 Updating documentation
  • 13:01 Marketing copy
  • 21:07 Sponsor: CloudBees Rollout
  • 22:25 Who bears the burden of copy?

Sponsor: CloudBees Rollout

Cloudbees Rollout is a secure, scalable feature management platform that allows engineers and software teams to accelerate mobile, web, and back-end development by giving them maximum control over their features in production. Create rich deployment rules based on percentages, custom attributes, or user segments to gradually roll new features out to users. Use multi-variate flags for A/B testing and nix misbehaving features with a kill switch. CloudBees Rollout is the safest way to deliver new features.

Check out the 14 day free trial and experience how CloudBees Rollout can help you rock every release.

Show Links

CodePen Links

The post 253: Copy appeared first on CodePen Blog.

XML Sitemaps Feature Plugin Open for Testing and Feedback

Thierry Muller, a Developer Relations Program Manager at Google, and several contributors posted an update on the XML sitemaps feature that may land in WordPress this year. After seven months of development, the team has made the XML Sitemaps feature plugin available on GitHub. It is currently open for testing and feedback. The plugin should also be available in the WordPress plugin directory by next week.

The project aims to ship a basic version of an XML sitemaps feature to all WordPress installations. It will also offer an API for plugin developers to manipulate. Therefore, sitemap plugins would not automatically disappear. Instead, plugins would offer users various options on how their sitemaps work.

A team created by Google, Yoast, and other contributors originally proposed XML sitemaps as a core WordPress feature in June 2019. Traditionally, WordPress has left this feature to plugins to implement, and many have filled this role over the years. However, several other major content management systems ship with sitemaps as part of their core codebase.

Many praised the initiative, such as WordPress project lead Matt Mullenweg. “This makes a lot of sense, looking forward to seeing the v1 of this in core and for it to evolve in future releases and cement WordPress’ well-deserved reputation of being the best CMS for SEO,” he said.

However, several people questioned whether WordPress should ship with XML sitemaps. Some were worried about performance and others felt like the feature should remain in plugins.

“At a high level, expanding the number of WordPress sites with Sitemaps ultimately speeds up content discoverability by search engines and re-crawl fresher content flagged by the lastmod date faster than a scheduled bot would,” Muller said of the primary reasons the feature belongs in core.

WordPress users may see this feature arrive in major update this year. “Ambitiously [version] 5.4,” said Muller of the release goal. “Realistically 5.5.”

The feature plugin currently indexes the following URLs for a site:

  • Homepage
  • Blog posts page (if not the homepage)
  • Posts and pages
  • Categories and tags
  • Custom post types
  • Custom taxonomies
  • Users/Authors

Custom post types and taxonomies are registered only if they are public. There is also a filter hook available to change which post types, taxonomies, and users are indexed. Ideally, WordPress would provide a registration flag for post types and taxonomies.

Solving the Performance Issues

One of the primary concerns with the initial proposal is how well a core sitemaps feature would perform and scale, particularly on larger sites. Without a full caching solution built into core, it presented some hurdles for the team.

“Solving the performance issue is not trivial, and we have looked into various solutions,” said Muller. “We believe that we landed on a solution that doesn’t need full caching and will still be scalable.”

For performance, there are two primary challenges:

  • The number of URLs per page.
  • The lastmod date in the index.xml file.

“Addressing the number of URLs per page is fairly trivial,” said Muller. “While sitemaps can have up to 50,000 URLs per sitemap, we found that capping it at 2,000 is acceptable from a performance perspective and totally acceptable from a search engine perspective.” The team decided to stick with a default of 2,000 URLs per sitemap and to provide a filter hook for plugins to alter if necessary.

Finding a solution for the lastmod date was not as easy. “We believe we found a good balance, which will be scalable and doesn’t open the can of worms that full caching exposes us to,” said Muller.

The solution the team implemented involved scheduling a cron task that runs twice daily (the frequency can be filtered by plugins). The cron job fetches the lastmod dates of each sitemap and stores them in the options table, which essentially works as a light caching solution.

“Relying on cron should be stable enough for small to medium websites,” said Muller. “Enterprise websites usually have server cron set up to more regularly ping WP Cron instead of relying on website visitors to trigger it. In fact, most managed hosting providers have that for all plans.”

If the team’s initial implementation is not well-rounded enough, they have been researching an alternative implementation that uses custom post types to store and update sitemap data. Two open GitHub tickets further explore performance that developers may want to check out: Issue #1 and Issue #39.

What Happens to Sites With Existing Sitemaps?

One question that remains unanswered is what happens when a user updates to WordPress 5.4/5.5 and already has a sitemap. There are likely millions of WordPress sites that are running a plugin or have some sort of sitemap solution in place.

“This is a question which we haven’t quite solved,” said Muller. “It is important to work with plugin authors, and in an ideal world, all plugins providing advanced sitemaps solutions would extend the core API. We would love to get feedback from the community on that one.”

WordPress must take care to avoid any major conflicts or indexing errors, or at least alleviate issues for the users who may be unaware of this upcoming feature.

Build a Web Application Based on Your Excel Files

Many companies have operated their business with Excel for decades. It is powerful yet easy to use, however, one of the biggest issues with Excel is that it is hard to integrate an Excel file with other systems and services, especially with a database. If you upload an Excel file as an attachment to a system and have to download it and open it up in Excel whenever you need to edit the file, you are just using Excel in a standalone manner. This is not an integrated solution.

In this article, I will show you how you can make your Excel file work seamlessly in a database-driven web application.

Four Layouts for the Price of One

Pretty notable when a tweet about a flexbox layouts gets 8K+ likes on Twitter!

That's "native" CSS nesting in use there as well, assuming we get that at some point and the syntax holds.

There was some feedback that the code is inscrutable. I don't really think so, to me it says:

  • All these inputs are allowed both to shrink and grow
  • There is even spacing around all of it
  • The email input should be three times bigger than the others
  • If it needs to wrap, fine, wrap.

A great use case for flexbox, which is the right layout mechanism when you aren't trying to be super precise about the size of everything.

There is a blog post (no byline 🤷‍♂️) with a more longwinded explanation.


This reminds me a lot of Tim Van Damme's Adaptive Photo Layout where photos lay themselves out with flexbox. They don't entirely keep their aspect ratios, but they mostly do, thanks to literally the flexibility of flexbox.

Here's a fun fork of the original.

It's like a zillion layouts for the price of one, and just a few lines of code to boot.

The post Four Layouts for the Price of One appeared first on CSS-Tricks.

Organizing Your Eclipse Foundation Open-Source Project Team

The Eclipse Foundation Development Process (AKA, the Eclipse Development Process, or EDP) says nothing about how teams should organize.

The EDP defines a committer role: committers are those developers who have the ability to make decisions for the project (e.g., push commits to project Git repositories and configure build servers). We often say that the committers are the ones with the real power: they're the ones that hold all of the keys to all of the project resources.

Building Blocks of DevOps: Developer Journeys

“Friction makes doing simple things difficult and difficult things impossible.” – Stephen Bungay

For all the right reasons, most mature Agile organizations put great emphasis on customer journeys, but what about your developer journeys? Do your developers have a smooth experience to deliver value?

Mule 4 MUnit multipart/form-data Payload

The following article gives an example of posting a multipart/form-data payload in MUnit. 

  • Mule version: 4.2.2
  • MUnit version: 2.2.2

This article assumes that you have already built a RAML and have a POST method accepting multipart/form-data content and asserting it can be done as per your requirements.

Practice GraphQL Queries With the State of JavaScript API

Learning how to build GraphQL APIs can be quite challenging. But you can learn how to use GraphQL APIs in 10 minutes! And it so happens I've got the perfect API for that: the brand new, fresh-of-the-VS-Code State of JavaScript GraphQL API.

The State of JavaScript survey is an annual survey of the JavaScript landscape. We've been doing it for four years now, and the most recent edition reached over 20,000 developers.

We've always relied on Gatsby to build our showcase site, but until this year, we were feeding our data to Gatsby in the form of static YAML files generated through some kind of arcane magic known to mere mortals as "ElasticSearch."

But since Gatsby poops out all the data sources it eats as GraphQL anyway, we though we might as well skip the middleman and feed it GraphQL directly! Yes I know, this metaphor is getting grosser by the second and I already regret it. My point is: we built an internal GraphQL API for our data, and now we're making it available to everybody so that you too can easily exploit out dataset!

"But wait," you say. "I've spent all my life studying the blade which has left me no time to learn GraphQL!" Not to worry: that's where this article comes in.

What is GraphQL?

At its core, GraphQL is a syntax that lets you specify what data you want to receive from an API. Note that I said API, and not database. Unlike SQL, a GraphQL query does not go to your database directly but to your GraphQL API endpoint which, in turn, can connect to a database or any other data source.

The big advantage of GraphQL over older paradigms like REST is that it lets you ask for what you want. For example:

query {
  user(id: "foo123") {
    name
  }
}

Would get you a user object with a single name field. Also need the email? Just do:

query {
  user(id: "foo123") {
    name
    email
  }
}

As you can see, the user field in this example supports an id argument. And now we come to the coolest feature of GraphQL, nesting:

query {
  user(id: "foo123") {
    name
    email
    posts { 
      title
      body
    }
  }
}

Here, we're saying that we want to find the user's posts, and load their title and body. The nice thing about GraphQL is that our API layer can do the work of figuring out how to fetch that extra information in that specific format since we're not talking to the database directly, even if it's not stored in a nested format inside our actual database.

Sebastian Scholl does a wonderful job explaining GraphQL as if you were meeting it for the first time at a cocktail mixer.

Introducing GraphiQL

Building our first query with GraphiQL, the IDE for GraphQL

GraphiQL (note the "i" in there) is the most common GraphQL IDE out there, and it's the tool we'll use to explore the State of JavaScript API. You can launch it right now at graphiql.stateofjs.com and it'll automatically connect to our endpoint (which is api.stateofjs.com/graphql). The UI consists of three main elements: the Explorer panel, the Query Builder and the Results panels. We'll later add the Docs panels to that but let's keep it simple for now.

The Explorer tab is part of a turbo-boosted version of GraphiQL developed and maintained by OneGraph. Much thanks to them for helping us integrate it. Be sure to check out their example repo if you want to deploy your own GraphiQL instance.

Don't worry, I'm not going to make you write any code just yet. Instead, let's start from an existing GraphQL query, such as the one corresponding to developer experience with React over the past four years.

Remember how I said we were using GraphQL internally to build our site? Not only are we exposing the API, we're also exposing the queries themselves. Click the little "Export" button, copy the query in the "GraphQL" tab, paste it inside GraphiQL's query builder window, and click the "Play" button.

Source URL
The GraphQL tab in the modal that triggers when clicking Export.

If everything went according to plan, you should see your data appear in the Results panel. Let's take a moment to analyze the query.

query react_experienceQuery {
  survey(survey: js) {
    tool(id: react) {
      id
      entity {
        homepage
        name
        github {
          url
        }
      }
      experience {
        allYears {
          year
          total
          completion {
            count
            percentage
          }
          awarenessInterestSatisfaction {
            awareness
            interest
            satisfaction
          }
          buckets {
            id
            count
            percentage
          }
        }
      }
    }
  }
}

First comes the query keyword which defines the start of our GraphQL query, along with the query's name, react_experienceQuery. Query names are optional in GraphQL, but can be useful for debugging purposes.

We then have our first field, survey, which takes a survey argument. (We also have a State of CSS survey so we needed to specify the survey in question.) We then have a tool field which takes an id argument. And everything after that is related to the API results for that specific tool. entity gives you information on the specific tool selected (e.g. React) while experience contains the actual statistical data.

Now, rather than keep going through all those fields here, I'm going to teach you a little trick: Command + click (or Control + click) any of those fields inside GraphiQL, and it will bring up the Docs panel. Congrats, you've just witnessed another one of GraphQL's nifty tricks, self-documentation! You can write documentation directly into your API definition and GraphiQL will in turn make it available to end users.

Changing variables

Let's tweak things a bit: in the Query Builder, replace "react" with "vuejs" and you should notice another cool GraphQL thing: auto-completion. This is quite helpful to avoid making mistakes or to save time! Press "Play" again and you'll get the same data, but for Vue this time.

Using the Explorer

We'll now unlock one more GraphQL power tool: the Explorer. The Explorer is basically a tree of your entire API that not only lets you visualize its structure, but also build queries without writing a single line of code! So, let's try recreating our React query using the explorer this time.

First, let's open a new browser tab and load graphiql.stateofjs.com in it to start fresh. Click the survey node in the Explorer, and under it the tool node, click "Play." The tool's id field should be automatically added to the results and — by the way — this is a good time to change the default argument value ("typescript") to "react."

Next, let's keep drilling down. If you add entity without any subfields, you should see a little squiggly red line underneath it letting you know you need to also specify at least one or more subfields. So, let's add id, name and homepage at a minimum. Another useful trick: you can automatically tell GraphiQL to add all of a field's subfields by option+control-clicking it in the Explorer.

Next up is experience. Keep adding fields and subfields until you get something that approaches the query you initially copied from the State of JavaScript site. Any item you select is instantly reflected inside the Query Builder panel. There you go, you just wrote your first GraphQL query!

Filtering data

You might have noticed a purple filters item under experience. This is actually they key reason why you'd want to use our GraphQL API as opposed to simply browsing our site: any aggregation provided by the API can be filtered by a number of factors, such as the respondent's gender, company size, salary, or country.

Expand filters and select companySize and then eq and range_more_than_1000. You've just calculated React's popularity among large companies! Select range_1 instead and you can now compare it with the same datapoint among freelancers and independent developers.

It's important to note that GraphQL only defines very low-level primitives, such as fields and arguments, so these eq, in, nin, etc., filters are not part of GraphQL itself, but simply arguments we've defined ourselves when setting up the API. This can be a lot of work at first, but it does give you total control over how clients can query your API.

Conclusion

Hopefully you've seen that querying a GraphQL API isn't that big a deal, especially with awesome tools like GraphiQL to help you do it. Now sure, actually integrating GraphQL data into a real-world app is another matter, but this is mostly due to the complexity of handling data transfers between client and server. The GraphQL part itself is actually quite easy!

Whether you're hoping to get started with GraphQL or just learn enough to query our data and come up with some amazing new insights, I hope this guide will have proven useful!

And if you're interested in taking part in our next survey (which should be the State of CSS 2020) then be sure to sign up for our mailing list so you can be notified when we launch it.

State of JavaScript API Reference

You can find more info about the API (including links to the actual endpoint and the GitHub repo) at api.stateofjs.com.

Here's a quick glossary of the terms used inside the State of JS API.

Top-Level Fields

  • Demographics: Regroups all demographics info such as gender, company size, salary, etc.
  • Entity: Gives access to more info about a specific "entity" (library, framework, programming language, etc.).
  • Feature: Usage data for a specific JavaScript or CSS feature.
  • Features: Same, but across a range of features.
  • Matrices: Gives access to the data used to populate our cross-referential heatmaps.
  • Opinion: Opinion data for a specific question (e.g. "Do you think JavaScript is moving in the right direction?").
  • OtherTools: Data for the "other tools" section (text editors, browsers, bundlers, etc.).
  • Resources: Data for the "resources" section (sites, blogs, podcasts, etc.).
  • Tool: Experience data for a specific tool (library, framework, etc.).
  • Tools: Same, but across a range of tools.
  • ToolsRankings: Rankings (awareness, interest, satisfaction) across a range of tools.

Common Fields

  • Completion: Which proportion of survey respondents answered any given question.
  • Buckets: The array containing the actual data.
  • Year/allYears: Whether to get the data for a specific survey year; or an array containing all years.

The post Practice GraphQL Queries With the State of JavaScript API appeared first on CSS-Tricks.

Apollo GraphQL without JavaScript

It's cool to see progressive enhancement being done even while using the fanciest of the fancy front-end technologies.

This is a button in a JSX React component that has a click handler applied directly to it that fires a data mutation Ajax request through Apollo GraphQL. That is about the least friendly environment for progressive enhancement I can imagine.

Hugo Giraudel writes that they do server-side rendering already, so the next tricky part is the click handler. Without JavaScript, the only mechanism we have for posting data is a <form>, so that's what they do. It submits to the /graphql endpoint with the data it needs to perform the mutation via hidden inputs, plus additional data on where to redirect upon success or failure.

Pretty neat.

Direct Link to ArticlePermalink

The post Apollo GraphQL without JavaScript appeared first on CSS-Tricks.

An Efficient Object Storage for JUnit Tests

One day I faced the problem with downloading a relatively large binary data file from PostgreSQL. There are several limitations to store and fetch such data (all restrictions could be found in official documentation). To resolve the problem it was suggested to find more suitable data storage.

For some internal reasons well known Amazon S3 bucket was chosen for this purpose. The choice affected the project's unit test base. It's still not possible to continue using light-weighted databases such as HSQL or H2 to implement tests. It is a key problem which we will try to resolve in this article.

Building Microservices Through Event-Driven Architecture, Part 8

During this article, I will talk about Event-Sourcing implementation of your application. This layer surrounds the domain and implements the uses cases (the application-specific business rules). It orchestrates the data flow and uses the domain model and infrastructures, and has no dependency on a database, UI or special frameworks.

You may also like: Building Microservices Through Event-Driven Architecture, Part 7

For our event-sourcing system, I will take all the uncommitted events from the aggregate and call a function of the repository which will have the responsibility to save the events in the eventstore. So I will call the function AppendAsync(EventStore @event) of IEventStoreRepository.

How to Achieve Energy Efficiency With IoT

Sustainability and efficiency are nowadays at the top of the public agenda. Vendors, suppliers, customers and the public at large are looking at products and services through the lens of environmental change. Companies are striving to meet increasing innovation demands in product development and customer service, while carefully juggling resources and striving for the lowest climate impact.

Maintaining a business that's simultaneously environmentally and commercially sustainable, across the entire supply chain, has never been more difficult nor more important.