teleren/devto huggingface dataset:
Test Environment Variables in Python
Tags: python, test, unittest, pytest
Published: 2020-05-19 13:01:43

---
title: Test Environment Variables in Python
published: true
date: 2020-02-18 00:00:00 UTC
tags: python, test, unittest, pytest
canonical_url: https://tech.serhatteker.com/post/2020-02/test-env-vars-in-python/
---

If you are working with environment variables you need to set, change or delete the values from the system for testing purposes. So how can we test them?

Let's assume that we have a function that gets a "secret" key from `os`
environment:

```py
# utilities.py
import os


def get_secret():
    """Simple retrieval function.
    Returns SECRET or raises OSError.
    """
    secret = os.getenv('SECRET', default=None)

    if secret is None:
        raise OSError("SECRET environment is not set.")

    return secret
```

One way for testing would be put an env var into config files of test like `tox.ini` or `pytest.ini`

```ini
# tox.ini
[testenv]
setenv = SECRET=top_secret
```

Another way would be using [pytest-env] plugin and adding it into `pytest.ini`:

```ini
# pytest.ini
[pytest]
env =
    HOME=~/tmp
    SECRET=top_secret
```

However these methods are not preferred since it violates isolating tests.

### Monkeypatching environment variables
Recommended way comes from `pytest` itself: `monkeypatch`. `pytest` provides a mechanism which gives the `setenv` and `delenv` methods.

First we set `SECRET` env var and test it, then testing `OSError` when `SECRET` not set. Since as we know; we always should test both "normal" and "failure" cases:

```py
# test_utilities.py
import pytest

from utilities import get_user


def test_get_user(monkeypatch):
    """Set the SECRET env var to assert the behavior."""
    monkeypatch.setenv("SECRET", "top_secret")

    assert get_user() == "top_secret"


def test_get_user_exception(monkeypatch):
    """Remove the SECRET env var and assert OSError is raised."""
    monkeypatch.delenv("SECRET", raising=False)

    with pytest.raises(OSError):
        _ = get_user()
```

You can also use `fixture` structures and share across them tests. For more info please go to: [pytest:testing env vars].

All done!

[pytest:testing env vars]: https://docs.pytest.org/en/latest/monkeypatch.html#monkeypatching-environment-variables
[pytest-env]: https://github.com/MobileDynasty/pytest-env
Monoliths are distributed systems too
Tags: distributedsystems, monolith, design
Published: 2020-02-17 23:56:18

---
title: Monoliths are distributed systems too
published: true
description: Monoliths contain some of the same concerns as microservices but the abstraction they provide obscures having to think about this
tags: distributed systems, monolith, design
---

The typical monolith application is actually a distributed system. The application typically interacts with a data store and often sits behind some kind of reverse proxy. Both these systems involve a two-way network connection with a monolithic app.

Typically in monolithic app development the main advantage we are getting is effectively benign neglect of the reality of the underlying infrastructure set up. We assume that our framework will handle a failure to interact with a datastore or an upstream proxy with a certain amount of grace.

For a developer they can effectively treat the entire execution of a handler as atomic and idempotent. Web frameworks though rarely provide features such as resource constraints, rate limitation and other handy features. With microservices you always need to handle these explicitly but in monolithic webapps these concerns tend to get pushed onto the front proxy which typically handle basic request timeouts (execution time constraints) and session and volume management.

In this respect only carefully coded, low volume applications do not have to care about distributed system concerns. All other "monoliths" inevitably require solution thinking that is very similar to that for microservices.

Thanks to [Sam Newman](https://samnewman.io/) for articulating this paradox so clearly.
Day 85: A Little More Time
Tags: hiphop, code, coding, lifelongdev
Published: 2020-02-17 23:29:56

_liner notes_:
- Saturday : Pretty packed day. Got up early to help out at the Orlando Developers Hackathon. People had some pretty good ideas. I wasn't able to stick around because I then went to go to a listening party for MidaZ the Beast new album "Where The Sidewalk Ends". Really good album. You can check it out at https://midazthebeast.bandcamp.com/album/where-the-sidewalk-ends

After that, I went to the statio to do the radio show. Had a great time as usual and we may have a special guest on a future show. Of course you can check out the show at https://kNOwBETTERHIPHOP.com

![Radio show episode image with the words February 15 2020, Rant The Jewels](https://dev-to-uploads.s3.amazonaws.com/i/ovlgzictegw2ng58xw57.jpg)

- Sunday : Tried to rest and catch up on some housework and side projects.

- Professional : Today, I worked on finishing up the blog post that I've been writing. Not sure why the writer's block, but I'm getting it done. Want to get it posted as a draft so that someone from Developer Education team and review it. Also got some stuff together to get ready for my trip to Atlanta tomorrow. Did some digging and there are a couple of meetups happening in Atlanta while I'm there that I want to attend and maybe give a quick demo. Found out that one of the conferences I submitted to go work got pushed further. It's good because it's in Germany and I would be in Europe already so I'm looking to spend a little more time over there. Hope it works out.

- Personal : Got some new shoes! If you know me, you know I'll keep using things until it falls apart. That's the state my shoes where getting to. haha. Since this weekend was pretty packed and I just got back from another trip, I have a lot of clothes I still need to iron and pack for my trip. Going to do that and get to bed early.

![Green cliffs of Fjaðrárgljúfur, Iceland with a river running through it and emptying it into the ocean](https://dev-to-uploads.s3.amazonaws.com/i/qbkdw82xuq99ynwp3b7f.png)

Tomorrow is going to be a long day. Driving to Atlanta and then going to a meetup. This will be the longest trip in the van so far. Need to make sure I have enough podcasts! Got some ironing and packing to do.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube mK5IS5rG3GQ %}
Context2D Canvas question. But is it Webgl?
Tags: javascript, help
Published: 2020-02-17 22:41:17

When canvas came out, you might or rather I might be forgiven for what I am about to say.

For the longest time I had believed that 2D context was somehow less powerful and slower than webgl and webgl2 contexts and perhaps even rendered on the CPU 😣, now that I write this I can see how silly this might sound. But I wonder if you can clear this up. Is context2d just webgl aka opengl but higher level and an API that is specific to JavaScript.

Next if context 2D is not transferable to other environments which utilize shaders, then the reasons to learn glsl are .... 

And lastly, can you use webgl and webgl2 in JavaScript without ever writing a line of glsl?
Great(er) goals for the future of Elixir
Tags: elixir, erlang, iot, future
Published: 2020-02-17 22:23:47

---
title: Great(er) goals for the future of Elixir
published: true
description: A talk from December 2019 by Dave Thomas at Gig City Conference
tags: elixir, erlang, IoT, future
---

Dave Thomas gave this inspirational and funny lecture about how the Elixir programming language could play a big part in creating the future.

The gist of this lecture is:
* making Elixir and the Phoenix framework "just" a better Rails is a low goal
* Elixir/Erlang have roots in Prolog
* Prolog allows you to program extremely declaratively
* if the BEAM community (Erlang + Elixir) dare to do new things the BEAM languages could play a big role in the Internet of Things, ambient computing and a host of other things
* if we _don't_ do it, it may well be done (very) poorly by other technologies, including security flaws

{% youtube ZHx_1yWkSiA %}

(Thanks @rhymes for the tip on YouTube markdown)
Alternating spotlights, Team directory | Module Monday 73
Tags: showdev, githunt, webdev, javascript
Published: 2020-02-17 22:21:00

---
title: Alternating spotlights, Team directory | Module Monday 73
published: true
description: Module Monday 73
tags: showdev, githunt, webdev, javascript
cover_image: https://res.cloudinary.com/component/image/upload/b_rgb:ffffff,c_lpad,h_350,w_800/v1581891988/spotlight_ewgvhu.gif
canonical_url: https://guide.anymod.com/module-monday/73.html
---

## Open source mods

You can use these mods (modules) on any website, web app, or anywhere else. There are hundreds more like these built & shared on [AnyMod](https://anymod.com).

Click a mod to see it along with its source code.

## Alternating spotlights
Spotlight content sections with responsiveness built in.
<a class="btn btn-sm" href="https://anymod.com/mod/alternating-sections-aldbdr?preview=true">View mod</a>
<a href="https://anymod.com/mod/alternating-sections-aldbdr?preview=true">
  <img src="https://res.cloudinary.com/component/image/upload/v1581891988/spotlight_ewgvhu.gif"/>
</a>

## Team directory
Keep your team page up to date without pushing new code every time.
<a class="btn btn-sm" href="https://anymod.com/mod/team-directory-orlook?preview=true">View mod</a>
<a href="https://anymod.com/mod/team-directory-orlook?preview=true">
  <img src="https://res.cloudinary.com/component/image/upload/v1581891983/team_vknbvz.gif"/>
</a>

## Fade in intro
Text and button fade followed by background.
<a class="btn btn-sm" href="https://anymod.com/mod/hero-w-background-ordoor?preview=true">View mod</a>
<a href="https://anymod.com/mod/hero-w-background-ordoor?preview=true">
  <img src="https://res.cloudinary.com/component/image/upload/v1581891985/hero_jto5jq.gif"/>
</a>

## Live countdown
Add your date for an instant countdown.
<a class="btn btn-sm" href="https://anymod.com/mod/simple-configurable-countdown-dknrlo">View mod</a>
<a href="https://anymod.com/mod/simple-configurable-countdown-dknrlo">
  <img src="https://res.cloudinary.com/component/image/upload/v1581891980/countdown_uhncay.gif"/>
</a>

## Icon cards
Showcase your value propositions with simple icons.
<a class="btn btn-sm" href="https://anymod.com/mod/icon-cards-mladbl">View mod</a>
<a href="https://anymod.com/mod/icon-cards-mladbl">
  <img src="https://res.cloudinary.com/component/image/upload/v1581891980/icon-cards-png_iykbbi.png"/>
</a>

<hr>

I post new mods from the community [here](https://dev.to/tyrw) every (Module) Monday -- I hope you find them useful!

Happy coding ✌️
Gotify notifications available with Diun 2.4
Tags: docker, registry, gotify, go
Published: 2020-02-17 22:17:22

---
title: Gotify notifications available with Diun 2.4
published: true
description: Receive notifications when a Docker image is updated on a Docker registry.
tags: docker,registry,gotify,golang
---

{% github crazy-max/diun %}

[**Diun**](https://github.com/crazy-max/diun) 2.4 🔔 has been released and adds support for Gotify notifications:

![Gotify notification](https://dev-to-uploads.s3.amazonaws.com/i/haibo9nz66ovf9tqktfj.png)

---

Support this project by [**becoming a sponsor on GitHub**](https://github.com/sponsors/crazy-max) 👏 or by making a [Paypal donation](https://www.paypal.me/crazyws) to ensure this journey continues indefinitely! 🚀

Thanks again for your support, it is much appreciated! 🙏
ODMLON - who owns your stack ?
Tags: oracle, odmlon, javascript, cloudf
Published: 2020-02-17 22:03:10

this cant wait - todays oracle developer meetup was a real eye opener

are you in media or retail ? then think twice - who really owns your stack ?

fine if you dont mind that fb & goog 'own' your ui (angular / react) frontend and its fine that your major competitor owns your backend (aws) ?

not so sure now ? then reconsider they actual 'open' solutions from ibm, microsoft and oracle instead

companies that actually want YOUR business to grow and not be consumed

if you are interested then watch this space over the next few months for non evil articles on oracle linux, oracle kvm, oraclejet, openshift, azure, oci, vscode, theia  and more
(Rust-lang) Creating a simple TODO service with Actix [Video] - Part 3
Tags: rust, webdev, tutorials, microservices
Published: 2020-02-17 21:55:17

[![Creating a simple TODO service with Actix - Part 3](https://img.youtube.com/vi/3vMxuM7ezEk/0.jpg)](https://youtu.be/3vMxuM7ezEk)

Watch previous parts
[Part 1](https://youtu.be/gQwA0g0NNSI)
[Part 2](https://youtu.be/e37NbhSm56o)
Reflections on mod 1
Tags: codingbootcamp, devblog
Published: 2020-02-17 21:47:19

---
title: Reflections on mod 1 
published: true
description: After 3 weeks I dive into what it has been like. How I feel about my future and most importantly how I feel I will adapt and thrive as a software engineer.
tags: codingbootcamp, devblog,  
series: Software Engineer Reflections
---

_Mod 1, week 3_ is nearing completion. We present our projects tomorrow (20200214) and I feel good about the project I worked on. 

The important thing though is how do I feel now that I have spent the last 3 weeks being a developer (esentially).... 

**_I feel great!!_** 

I feel that this choice to take 15 weeks to focus deeply on my career transition is not only an extended form of healthy self-care but a really good investment in my own future.
WordPress REST API Cors Issues
Tags: development, wordpress
Published: 2020-02-17 22:52:02

---
title: WordPress REST API Cors Issues
published: true
date: 2020-02-17 21:35:31 UTC
tags: Development,WordPress
canonical_url: https://robertmarshall.dev/blog/wordpress-rest-api-cors-issues
---

Most up to date post is here: https://robertmarshall.dev/blog/wordpress-rest-api-cors-issues

Are you using WordPress as a headless CMS? Are you trying to work with REST API, but be as secure as possible? Are you getting the following CORS header errors:

> “Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

> “X has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”

I found this as well! Mainly due to WordPress not the simplest thing to use when dealing with the REST API and CORS security.

The solution is this:

```
<?php add_action('init', 'handle_preflight');
function handle_preflight() {
    $origin = get_http_origin();
    if ($origin === 'https://yourfrontenddomain') {
        header("Access-Control-Allow-Origin: " . HEADLESS_FRONTEND_URL);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
        if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
            status_header(200);
            exit();
        }
    }
}
add_filter('rest_authentication_errors', 'rest_filter_incoming_connections');
function rest_filter_incoming_connections($errors) {
    $request_server = $_SERVER['REMOTE_ADDR'];
    $origin = get_http_origin();
    if ($origin !== 'https://yourfrontenddomain') return new WP_Error('forbidden_access', $origin, array(
        'status' => 403
    ));
    return $errors;
}
?>
```

Hope it helps!
5 Web Discoveries Which Are Pretty Awesome
Tags: webdev, bash, javascript, devops
Published: 2020-02-17 21:21:27

This is my second post in the series **5 Web Discoveries**, in which I want to share great web resources with you. If you want more, just have a look at Turtle community (https://turtle.community), where you can find handy tools for developers which will make your life a lot easier.


### 1) CyberChef - One webapp for all those little annoying tasks in your everyday dev life

This tool (https://gchq.github.io/CyberChef/) allows you to quickly perform recurring tasks during development. Date conversion, encryption, hashing, image manipulation, parsing and many more. Just think of it as a single GUI, which puts the most used algorithms in programming at your fingertips. I use it very often to quickly convert from/to base64 or for unix timestamps.


### 2) Explainshell - Quickly understand what your shell command is really doing

Have you ever wondered what again `tar -abcdefghijkl...` was doing? Explainshell (https://explainshell.com/) let's you just type in your shell command, disassembles all the options, parameters and arguments and matches them to their explanation from the help texts. So with this tool there is no more grepping through man pages or help texts. In most cases I use it to lookup the many options of `rsync`.


### 3) Bundlephobia - Check the weight of your npm packages before including them in your project

Performance matters, especially for your website. This tool (https://bundlephobia.com/) lets you quickly check the bundle size of every npm package. When looking for some nice npm package, which does some particular job I always check the impact on my project. Sometimes they bring in so many dependencies that you'll want to consider alternatives.


### 4) Dicebear Avatars - Open source avatars for your website

These avatars (https://avatars.dicebear.com/) are very handy if you need an initial placeholder image for your users. This package exposes an API and let's you choose between different styles of SVG avatars (robots, humans, initials, ...). The SVGs are created from a simple seed so that you do not need to store anything in your database.

### 5) Chart.js - Simple yet flexible JavaScript charting for designers & developers

With this library (https://www.chartjs.org/) you can create awesome looking charts in your frontend. It supports many different types of graphs like e.g. scatter plots, pie charts, multi-axes plots and so on. The documentation features many examples and you can even animate all your data.
Last Weeks' Top 5 Unseen articles
Tags: top7, bestofdev, healthydebate
Published: 2020-02-17 21:18:19

dev.to is a great place to share your ideas, projects, content and start a good discussion. However, due to the large amont of published artices every day, some good articles get lost.

So here are the articles I enjoyed reading last week which didn't get a ton of reaction (probably becase nobody saw them). Maybe there is something interesting for you to read and start your week.

###UI 🖼️

Everybody loves great UI, right? Lets' face it, getting time to optimze your UI can be a hard sell at a busy company. [Vani Shivanand](https://dev.to/svaani) gives some tips to negotiate for UI optimization, focusing on performance improvements.

{% link https://dev.to/svaani/negotiating-for-ui-optimization-34fl %}

###IndieWeb 🕸️

IndieWeb is a movement focusing on making better and more connected experiences for publishing and consuming content. One part of that are webmontions, a way to inform content creators when and where their articles get discussed. [Shawn swyx wang](https://dev.to/swyx) published a good piece on how to implement webmentions clientside using webmentions.io in Svelte.

{% link https://dev.to/swyx/clientside-webmentions-3dph %}

###UX 🤕

You know these header bars which move away when scrolling down and appear when scrolling up? [Waylon Walker](https://dev.to/waylonwalker) shares his experiences doing that in a React app, using React Headroom. Spoiler: It seemed to have been an awesome experience.

{% link https://dev.to/waylonwalker/i-just-added-react-headroom-to-my-site-2c51 %}

###Career boost 🏎️

There can be a misalignment between the wish to learn new technologies and the work you do at work. [Ndy](https://dev.to/ndy40) gives us his thoughts on the topic. One motivating point he makes is, that with the vast landscape in tech related jobs there's probably some need for everything you may be great at.

{% link https://dev.to/ndy40/experience-is-all-about-learning-and-opportunities-374n %}

###Work-Life balance 🌅

So you have the possibility to work from home? That's fantastic, but there may be some challenges to that. [Nazanin Delam](https://dev.to/nazanindelam) has a list with tips on how to be productive in a Work From Home setting.

{% link https://dev.to/nazanindelam/wfh-effectively-1cl7 %}

Did you find something you missed in that list? Have your own Unseen Articles, which are worth a read? Let me know in the comments!
Resources on 14 years of Java Changes?
Tags: java, help
Published: 2020-02-17 21:11:37

All, I'm looking for some very high-level resources as to how Java has changed since 2006, the last time I worked with the language.

I'm specifically curious as to new language features and how the language may have evolved similarly or differently to C# as I'm a .NET developer.

I realize the question is vague and open-ended, but hopefully someone can point me in a right direction or give me a pie in the sky summary. Just looking for awareness, not implementation details.
Node.js + TypeScript Starter For Your Next Project
Tags: node, typescript, webdev, beginners
Published: 2020-02-17 21:01:16

If you're a beginner that wants to learn TypeScript and Node, this starter may be the best choice for you. You won't need to configure anything in order to be able to develop and build your project, just clone it, install the dependencies and launch the development script, the rest is in your hands!

The current configuration handles polyfills for you using Babel, lints your code using ESLint, and makes sure everything is correct when you attempt to submit a new commit.

Here's the repo: [HorusGoul/node-ts-starter](https://github.com/HorusGoul/node-ts-starter)

{% github HorusGoul/node-ts-starter %}

I hope you like it, make me know if there's anything you'd like to see included or about any issue that you encounter while using it.

## 👋
Automatically version and deploy your documentation with github actions
Tags: github, docs, versioning, githubaction
Published: 2020-02-17 20:49:55

---
title: Automatically version and deploy your documentation with github actions
published: true
description: Automatically version your docs in a single github branch and deploy them as static assets
tags: github, docs , versioning , github-action
---
Hey guys,

I created two github actions that allow you to automatically version and deploy your documentation.

You get the simplicity of keeping your documentation versioned in git, without the annoyance of having huge PR's due to auto-generated-doc updates.

Right now the only hosting provider implemented is netlfiy, however more are planned.

https://github.com/bobrown101/version-docs

https://github.com/bobrown101/deploy-branch

Here is an example of how you would use it within your github repo:
```
name: Version and Deploy docs
on: push
jobs:
  CI:
    runs-on: ubuntu-latest
    env:
      CI: true
    steps:
    - name: Generate docs
      run: yarn docs
    - name: Version docs
      uses: bobrown101/version-docs@v2.1.0
      with:
        github-token: ${{ secrets.GITHUB_TOKEN }}
        doc-location: docs
        doc-branch: docs
    - name: Deploy docs
      uses: bobrown101/deploy-branch@v2.0.0
      with:
        provider: NETLIFY
        netlify-auth-token: ${{ secrets.NETLIFY_AUTH_TOKEN }}
        netlify-site-id: <<siteid>>
        branch: docs
        github-token: ${{ secrets.GITHUB_TOKEN }}

```

I would appreciate any feedback and stars on github.

Thanks,

Brady
ColdFusion UDF to identify Test Credit Card Numbers
Tags: coldfusion, cfml, validation
Published: 2020-02-17 20:48:10

I wrote a simple ColdFusion UDF to test if a credit card number matches test card numbers provided by various credit card merchants (as opposed to only validating against the Luhn algorithm.)

{% gist https://gist.github.com/JamoCA/6157875 %}