MoreRSS

site iconThe Practical DeveloperModify

A constructive and inclusive social network for software developers.
Please copy the RSS to your reader, or quickly subscribe to:

Inoreader Feedly Follow Feedbin Local Reader

Rss preview of Blog of The Practical Developer

Pare de Executar Toda a Sua Suite de Testes em Cada Commit 🚫🧪

2026-02-11 03:18:09

Todos nós já passamos por isso. Você faz uma pequena correção em um arquivo, commita suas mudanças e fica assistindo toda a sua suite de testes rodar pelos próximos 5 minutos. Familiar?

E se eu te dissesse que existe uma maneira de executar apenas os testes que estão realmente relacionados às suas mudanças? Conheça o test-staged.

O Problema

Executar toda a sua suite de testes antes de cada commit é:

  • Lento - Desperdiçando tempo precioso de desenvolvimento
  • 😤 Frustrante - Quebrando seu estado de fluxo
  • 🔄 Redundante - Testando código que você nem tocou

A maioria dos desenvolvedores:

  1. Pula os testes completamente (perigoso!)
  2. Espera por longas execuções de testes (frustrante!)
  3. Faz push e torce para o CI pegar os problemas (arriscado!)

Tem que haver uma maneira melhor.

A Solução: test-staged

test-staged é como o lint-staged, mas para testes. Ele identifica inteligentemente quais testes estão relacionados às suas mudanças em stage e executa apenas esses.

Quão Inteligente É?

test-staged usa diferentes estratégias dependendo do seu test runner:

  • Jest/Vitest: Usa análise nativa de grafo de dependências (--findRelatedTests / vitest related)
  • Mocha/Ava: Mapeia inteligentemente arquivos fonte para arquivos de teste (ex: user.tsuser.test.ts, src/api/users.tssrc/api/__tests__/users.test.ts)

Começando em 30 Segundos

A instalação é moleza:

npm install -D test-staged
# ou
pnpm add -D test-staged
# ou
yarn add -D test-staged
# ou
bun add -D test-staged

E é isso. Sério. É zero configuração por padrão.

Configure como um Hook de Pre-Commit

A mágica acontece quando você combina com o Husky:

# Instale o husky
npm install -D husky
npx husky init

# Adicione test-staged ao pre-commit
echo "npx test-staged" > .husky/pre-commit

Agora cada commit vai:

  1. ✅ Executar apenas testes relacionados às suas mudanças
  2. ⚡ Completar em segundos ao invés de minutos
  3. 🛡️ Bloquear commits se os testes falharem

Exemplos do Mundo Real

Exemplo 1: Mudança em um Único Arquivo

Você está trabalhando em uma funcionalidade de autenticação de usuário:

# Você modificou:
git add src/auth/login.ts

# test-staged executa APENAS:
src/auth/__tests__/login.test.ts
src/integration/__tests__/auth-flow.test.ts  # (porque importa login.ts)

# NÃO executa:
src/payments/__tests__/*.test.ts  ❌
src/dashboard/__tests__/*.test.ts  ❌
(e mais de 200 testes não relacionados)

Resultado: Testes completam em 3 segundos ao invés de 2 minutos.

Exemplo 2: Refatorando Utilitários

Você refatorou uma função utilitária:

# Você modificou:
git add src/utils/formatDate.ts

# test-staged automaticamente encontra TODOS os testes que dependem dela:
src/utils/__tests__/formatDate.test.ts
src/components/__tests__/DatePicker.test.ts
src/pages/__tests__/Dashboard.test.ts

Inteligente o suficiente para capturar dependências indiretas, rápido o suficiente para te manter produtivo.

Exemplo 3: Suporte a Monorepo

Trabalhando em um monorepo? test-staged te cobre:

# Você está em packages/ui
git add Button.tsx

# Executa apenas:
packages/ui/__tests__/Button.test.tsx

# Não executa testes de:
packages/api/  ❌
packages/cli/  ❌

Por Que Você Vai Amar

🎯 Zero Configuração

Detecta automaticamente:

  • Seu gerenciador de pacotes (npm, pnpm, yarn, bun)
  • Seu test runner (Jest, Vitest, Mocha, Ava)
  • Sua estrutura de projeto (monorepo ou pacote único)

⚡ Extremamente Rápido

Em um projeto típico com 500+ testes:

  • Antes: 2-3 minutos por commit
  • Depois: 2-5 segundos por commit

Isso é uma melhoria de 36x no uso do mundo real.

🧠 Realmente Inteligente

Para Jest e Vitest, usa o grafo de dependências nativo:

// Se você mudar userService.ts
// ele encontra testes que o importam:
import { createUser } from './userService'
import { validateUser } from './userService'

Para Mocha e Ava, usa correspondência de padrões:

src/models/user.ts → src/models/user.test.ts
src/api/users.ts   → src/api/__tests__/users.test.ts
lib/parser.ts      → lib/parser.spec.ts

🛠️ Personalizável Quando Necessário

Embora funcione sem configuração, você pode customizá-lo:

// package.json
{
  "test-staged": {
    "runner": "jest",
    "mode": "related",
    "testExtensions": [".test", ".spec", ".e2e"]
  }
}

Ou crie um .test-stagedrc.json:

{
  "runner": "vitest",
  "testExtensions": [".test", ".spec", "Test", "E2E"]
}

Test Runners Suportados

Runner Método de Detecção
Vitest Nativo vitest related (grafo de dependências)
Jest Nativo --findRelatedTests (grafo de dependências)
Mocha Correspondência de padrões de arquivo
Ava Correspondência de padrões de arquivo

Mais runners em breve!

A Experiência do Desenvolvedor

Veja como fica seu fluxo de trabalho:

# Faça suas mudanças
vim src/components/Button.tsx

# Coloque em stage
git add src/components/Button.tsx

# Commit (test-staged executa automaticamente via hook de pre-commit)
git commit -m "fix: estado hover do botão"

# Saída:
Running tests for staged files...
✓ src/components/__tests__/Button.test.tsx (2 tests) 0.8s

Tests passed! ✨
[main abc1234] fix: estado hover do botão

Sem comandos de teste manuais. Sem espera. Sem commits quebrados.

Perguntas Comuns

P: E se eu quiser executar todos os testes?

R: Apenas pule o hook: git commit --no-verify ou execute sua suite de testes manualmente.

P: Funciona com CI?

R: Sim! Seu CI ainda deve executar a suite de testes completa. test-staged é para velocidade no desenvolvimento local.

P: E quanto a testes de integração/E2E?

R: test-staged vai encontrá-los se eles importarem seus arquivos modificados. Você também pode customizar quais testes executar.

P: Posso usar sem hooks do Git?

R: Absolutamente! Apenas execute npx test-staged manualmente quando quiser.

Experimente Hoje

Comece em menos de um minuto:

npm install -D test-staged husky
npx husky init
echo "npx test-staged" > .husky/pre-commit

Depois faça um commit e veja a mágica acontecer. ✨

Links

Resumindo

Se você ainda está executando toda sua suite de testes em cada commit, está desperdiçando tempo. test-staged te dá:

  • Commits mais rápidos (segundos ao invés de minutos)
  • 🎯 Melhor foco (teste apenas o que mudou)
  • 🛡️ Código mais seguro (testes realmente executam ao invés de serem pulados)
  • 🚀 Melhor DX (zero configuração, simplesmente funciona)

Experimente e me diga o que você achou! Seu eu do futuro vai te agradecer. 🙌

Você já experimentou test-staged? Qual é sua estratégia atual de testes em pre-commit? Compartilhe nos comentários abaixo! 👇

AI in the Future

2026-02-11 03:16:13

Here are my two cents on the current AI era.

Before reading this, understand that I am not a thought leader, nor have I spent time with founders in Silicon Valley or leaders in major tech companies. Everything below reflects my personal perspective, based on what I have read about AI over the last few months, my experience using AI tools, and my exposure to sci-fi movies involving artificial intelligence.

I was introduced to ChatGPT through dev.to and Instagram when it launched. I saw a few reels and saw memes in Meme Monday. After a quick Google search, I discovered that GPT was not yet available in India. Later, another creator posted a reel announcing its availability, and I signed up and started using it.

I initially used ChatGPT to refactor legacy code written with class-based components and an older version of Next.js into functional components using modern practices. Tasks that once took days of code review and documentation lookup were reduced to a few hours. Early GPT models were unreliable and often repetitive, but newer versions are noticeably more capable, more natural in tone, trained on larger datasets, and suggest follow-up questions on their own.

Future of Developers in a World of GenAI

What will happen to developers or anyone whose job depends on technology as GenAI improves at an exponential rate?

Short answer: not much.

Long answer: AI has changed how developers work, not whether developers are needed.

Before GenAI, developers memorized syntax, patterns, and snippets. That repetition built deep familiarity with code. Now, much of that recall is outsourced to prompts.

But writing code has never been the hardest part.

Understanding code is.

Understanding comes from writing, breaking, debugging, tracing variables, inspecting logs, and spending hours figuring out why something fails.

AI cannot do this inside your real production environment. It does not see your full system. It does not feel the consequences of a bad deploy.

AI is fundamentally a response generator. It does nothing without a prompt. It is just another software service.

Web and app development is more than writing code. If coding were all that mattered, anyone with Claude or GPT would already be launching profitable products. That is not happening.

Why AGI Is Not Coming Soon

My definition of AGI is a system with a brain-like structure, composed of neurons similar to the human brain, capable of thinking independently and acting without constant user input.

Even if companies release something labeled “AGI,” it will likely be a much smarter version of today’s models, trained on more parameters, possibly with vision and real-time perception. It will be demonstrated in controlled environments to create the impression of general intelligence, much like polished product demos today.

True AGI resembles Skynet (Terminator), Ultron (Avengers), or the robots in I, Robot: machines with independent consciousness and autonomous decision-making.

We do not have hardware capable of mimicking even a fraction of the human brain’s processing capacity. Research into brain-like computing is ongoing, but we are far from replicating it.

Why AGI Won’t Replace Developers

For AGI to replace developers, it must:

  • Accept vague business requirements
  • Ask clarifying questions on its own
  • Design architecture
  • Write code with extremely high accuracy
  • Test and iterate autonomously
  • Current GenAI cannot do this.

Example: If you ask GenAI, “Create a signup feature,” it typically generates a form with name, email, password fields, and a backend endpoint. But the user never specified:

  • Client-side vs server-side validation
  • Mandatory vs optional fields
  • Encryption standards
  • Authentication method

A human developer asks these questions. Once requirements are clarified, an outline is created, approved, implemented, tested, reviewed, and iterated until defects reach zero. This entire workflow requires judgment, prioritization, and accountability.

Even if something called AGI appears within a year or two, it will still resemble advanced GenAI, not a human coworker.

Bottom line: AI will not replace developers anytime soon.

What Current GenAI Really Is

Think of GenAI as a powerful machine in a factory. The machine produces output. Workers (humans) inspect results, correct errors, and supply better input. Without workers, the machine does nothing.

Claude, GPT, and Gemini cannot write code without prompts.

Jobs Most Impacted by AI

  1. Customer support chat.
  2. Basic copywriting.
  3. Simple content generation.
  4. Basic-to-intermediate graphic design (banners, posters, social media creatives).

Many companies now generate these assets in-house using image models. Vendors who previously specialized in this work are only contacted when AI output is not good enough or requires heavy refinement.

There are likely more affected roles. Do not treat these examples as exhaustive.

How to Survive in the AI Era

Same rules as before.

  1. Learn fundamentals.
  2. Understand systems.
  3. Know how things break.
  4. Know how to fix them.

Layoffs existed before AI.
They will exist after AI.

The future is not fewer developers.
The future is developers who think better and move faster.

Stop Running Your Entire Test Suite on Every Commit 🚫🧪

2026-02-11 03:15:59

We've all been there. You make a small fix in one file, commit your changes, and watch as your entire test suite runs for the next 5 minutes. Sound familiar?

What if I told you there's a way to run only the tests that are actually related to your changes? Enter test-staged.

The Problem

Running your complete test suite before every commit is:

  • Slow - Wasting precious development time
  • 😤 Frustrating - Breaking your flow state
  • 🔄 Redundant - Testing code you didn't even touch

Most developers either:

  1. Skip tests entirely (dangerous!)
  2. Wait through long test runs (frustrating!)
  3. Push and pray the CI catches issues (risky!)

There has to be a better way.

The Solution: test-staged

test-staged is like lint-staged, but for tests. It intelligently identifies which tests are related to your staged changes and runs only those.

How Smart Is It?

test-staged uses different strategies depending on your test runner:

  • Jest/Vitest: Uses native dependency graph analysis (--findRelatedTests / vitest related)
  • Mocha/Ava: Intelligently maps source files to test files (e.g., user.tsuser.test.ts, src/api/users.tssrc/api/__tests__/users.test.ts)

Getting Started in 30 Seconds

Installation is a breeze:

npm install -D test-staged
# or
pnpm add -D test-staged
# or
yarn add -D test-staged
# or
bun add -D test-staged

And that's it. Seriously. It's zero-config by default.

Set Up as a Pre-Commit Hook

The magic happens when you combine it with Husky:

# Install husky
npm install -D husky
npx husky init

# Add test-staged to pre-commit
echo "npx test-staged" > .husky/pre-commit

Now every commit will:

  1. ✅ Only run tests related to your changes
  2. ⚡ Complete in seconds instead of minutes
  3. 🛡️ Block commits if tests fail

Real-World Examples

Example 1: Single File Change

You're working on a user authentication feature:

# You modified:
git add src/auth/login.ts

# test-staged runs ONLY:
src/auth/__tests__/login.test.ts
src/integration/__tests__/auth-flow.test.ts  # (because it imports login.ts)

# NOT running:
src/payments/__tests__/*.test.ts  ❌
src/dashboard/__tests__/*.test.ts  ❌
(and 200+ other unrelated tests)

Result: Tests complete in 3 seconds instead of 2 minutes.

Example 2: Refactoring Utilities

You refactored a utility function:

# You modified:
git add src/utils/formatDate.ts

# test-staged automatically finds ALL tests that depend on it:
src/utils/__tests__/formatDate.test.ts
src/components/__tests__/DatePicker.test.ts
src/pages/__tests__/Dashboard.test.ts

Smart enough to catch indirect dependencies, fast enough to keep you productive.

Example 3: Monorepo Support

Working in a monorepo? test-staged has you covered:

# You're in packages/ui
git add Button.tsx

# Only runs:
packages/ui/__tests__/Button.test.tsx

# Doesn't run tests from:
packages/api/  ❌
packages/cli/  ❌

Why You'll Love It

🎯 Zero Configuration

It automatically detects:

  • Your package manager (npm, pnpm, yarn, bun)
  • Your test runner (Jest, Vitest, Mocha, Ava)
  • Your project structure (monorepo or single package)

⚡ Lightning Fast

On a typical project with 500+ tests:

  • Before: 2-3 minutes per commit
  • After: 2-5 seconds per commit

That's a 36x speed improvement in real-world usage.

🧠 Actually Intelligent

For Jest and Vitest, it uses the native dependency graph:

// If you change userService.ts
// it finds tests that import it:
import { createUser } from './userService'
import { validateUser } from './userService'

For Mocha and Ava, it uses pattern matching:

src/models/user.ts → src/models/user.test.ts
src/api/users.ts   → src/api/__tests__/users.test.ts
lib/parser.ts      → lib/parser.spec.ts

🛠️ Customizable When Needed

While it works out-of-the-box, you can customize it:

// package.json
{
  "test-staged": {
    "runner": "jest",
    "mode": "related",
    "testExtensions": [".test", ".spec", ".e2e"]
  }
}

Or create a .test-stagedrc.json:

{
  "runner": "vitest",
  "testExtensions": [".test", ".spec", "Test", "E2E"]
}

Supported Test Runners

Runner Detection Method
Vitest Native vitest related (dependency graph)
Jest Native --findRelatedTests (dependency graph)
Mocha File pattern matching
Ava File pattern matching

More runners coming soon!

The Developer Experience

Here's what your workflow looks like:

# Make your changes
vim src/components/Button.tsx

# Stage them
git add src/components/Button.tsx

# Commit (test-staged runs automatically via pre-commit hook)
git commit -m "fix: button hover state"

# Output:
Running tests for staged files...
✓ src/components/__tests__/Button.test.tsx (2 tests) 0.8s

Tests passed! ✨
[main abc1234] fix: button hover state

No manual test commands. No waiting. No broken commits.

Common Questions

Q: What if I want to run all tests?

A: Just bypass the hook: git commit --no-verify or run your test suite manually.

Q: Does it work with CI?

A: Yes! Your CI should still run the full test suite. test-staged is for local development speed.

Q: What about integration/E2E tests?

A: test-staged will find them if they import your changed files. You can also customize which tests run.

Q: Can I use it without Git hooks?

A: Absolutely! Just run npx test-staged manually whenever you want.

Try It Today

Get started in less than a minute:

npm install -D test-staged husky
npx husky init
echo "npx test-staged" > .husky/pre-commit

Then make a commit and watch the magic happen. ✨

Links

The Bottom Line

If you're still running your entire test suite on every commit, you're wasting time. test-staged gives you:

  • Faster commits (seconds instead of minutes)
  • 🎯 Better focus (test only what changed)
  • 🛡️ Safer code (tests actually run instead of being skipped)
  • 🚀 Better DX (zero config, just works)

Give it a try and let me know what you think! Your future self will thank you. 🙌

Have you tried test-staged? What's your current pre-commit testing strategy? Share in the comments below! 👇

Code is the execution. Thinking is the strategy.

2026-02-11 03:08:40

💡 The Smart Student’s Epiphany

Recently, while studying, I realized something that completely changed the way I look at SQL.

In one class, I watched the instructor building complex queries and thought:

“He doesn’t start with SQL… he starts with THINKING.”

And that’s when it clicked.

We spend a lot of time learning syntax, but we almost never learn how to think before coding.

And that makes all the difference.

🎯 The problem: why do we freeze?

If you study SQL, you’ve probably been here:

  1. You receive a complex problem
  2. You open the SQL editor
  3. You type SELECT * FROM...
  4. Freeze. “Now what?”
  5. You start trying some JOINs
  6. You get confused
  7. You feel frustrated
  8. You end up on Stack Overflow

Result: messy code, wrong results, and wasted time.

For a long time, I thought this was:

  • lack of practice
  • or lack of technical knowledge

But it wasn’t.

The problem was before SQL.

👉 In the next post, I’ll share the analogy that finally organized this way of thinking —

and why jumping straight into code is often exactly what slows us down the most.

#ThinkBeforeYouCode #SQL #RealLearning #DataEngineering #Data

WireGuard no TP-Link Omada ER605: O Guia Definitivo

2026-02-11 02:57:27

Criando sua VPN passo a passo (Roteador + Cliente)

Se você já tentou usar OpenVPN ou L2TP em um homelab, sabe que a configuração pode ser trabalhosa e o desempenho nem sempre é o ideal.
O WireGuard resolve isso com uma abordagem moderna: é um protocolo de código aberto extremamente simples, rápido e que utiliza criptografia de última geração.

Por operar diretamente no kernel do sistema, ele atinge velocidades muito superiores aos protocolos tradicionais. Além disso, lida perfeitamente com trocas de rede (como mudar do Wi-Fi para o 4G) sem perder a conexão.

📌 Requisitos prévios

Para seguir este guia, você precisa de:

Firmware atualizado no TP-Link ER605 (mínimo hardware v2.0)

Aplicativo WireGuard instalado no dispositivo cliente (celular ou notebook)

Opcional: Serviço de DDNS configurado (recomendado para IP dinâmico)

1️⃣ Criando a Interface WireGuard no ER605

No painel do roteador ou da controladora Omada, acesse:

VPN → WireGuard → WireGuard → Add

Configure a interface:

Name: vpn_client

MTU: 1420 (valor ideal para evitar fragmentação de pacotes)

Listen Port: 51825

Local IP Address: 10.100.1.1

Status: Enable

🔒 Atenção
As chaves Private Key e Public Key são geradas automaticamente pelo roteador.
Você precisará copiar apenas a Public Key para configurar o cliente no próximo passo.
A Private Key nunca deve sair do roteador.

2️⃣ Gerando a configuração no cliente WireGuard

Antes de cadastrar o cliente no roteador, precisamos gerar as chaves do próprio dispositivo.

No aplicativo WireGuard:

  1. Clique no ícone “+”

  2. Selecione Add Empty Tunnel

Isso gera automaticamente uma PrivateKey e uma PublicKey para o cliente.

Monte a configuração seguindo este modelo:

[Interface]
PrivateKey =
Address = 10.100.1.2/32
DNS = 8.8.8.8

[Peer]
PublicKey =
AllowedIPs = 192.168.0.0/24
Endpoint = lainux.hopto.org:51825

Explicando os campos

Address (/32)
Define um IP fixo para este cliente dentro do túnel VPN.

AllowedIPs

192.168.0.0/24 → acesso apenas à rede local (Split Tunnel)

0.0.0.0/0 → todo o tráfego passa pela VPN (Full Tunnel)

Endpoint
Endereço público ou DDNS do roteador + porta WireGuard.

3️⃣ IP fixo vs DDNS no WireGuard (muito importante)

Você pode configurar o WireGuard apontando diretamente para o IP público do roteador ou usando um DDNS. A escolha depende do tipo de IP fornecido pela sua operadora.

Quando usar IP público direto

Endpoint = 179.20.20.22:51825

Funciona quando:

Você possui IP público fixo, ou

O IP muda muito raramente

Nesse cenário, usar o IP direto não é um problema.

Quando usar DDNS (recomendado)

Na maioria dos links residenciais, o IP é dinâmico e pode mudar a qualquer momento.
Quando isso acontece, o WireGuard não consegue mais localizar o roteador e a VPN para de funcionar.

A solução correta é usar DDNS (Dynamic DNS):

Endpoint = vpn-homelab.ddns.net:51825

Assim, mesmo que o IP mude, o nome DNS continuará apontando para o endereço correto.

👉 Guia completo de DDNS no ER605:
Como configurar DDNS no TP-Link ER605 usando NO-IP
https://dev.to/ferradas/como-configurar-ddns-no-tp-link-er605-no-ip-37a5

📌 Boa prática:
Se você usa WireGuard para acesso remoto, DDNS não é opcional — faz parte da arquitetura.

4️⃣ Cadastrando o Peer no roteador

Agora volte ao ER605 para autorizar a conexão do cliente:

VPN → WireGuard → Peers → Add

Configure:

Interface: vpn_client

Public Key: chave pública gerada no app WireGuard do cliente

Endpoint: IP público ou DDNS (ex: homelab.hopto.org)

Endpoint Port: 51825

Allowed Address: 10.100.1.2/32

Persistent Keepalive: 25

Status: Enable

Por que isso é importante?

Allowed Address (/32)
Garante IP fixo e isolamento por cliente.

Persistent Keepalive = 25
Essencial para conexões atrás de NAT, CGNAT, Wi-Fi público ou 4G/5G.

5️⃣ Testando a conexão

  1. Salve as configurações no roteador

  2. No cliente (fora da rede local), clique em Activate

  3. No ER605, verifique:

Campo Last Handshake atualizado

Contadores de RX/TX Bytes aumentando

Se isso acontecer, sua VPN está funcionando corretamente ✅

Conclusão

O WireGuard no TP-Link Omada ER605 é uma solução moderna, rápida e extremamente estável para acesso remoto ao homelab.

Com menos complexidade que OpenVPN e desempenho superior, ele é ideal para cenários com mobilidade, NAT e redes residenciais.

Se você ainda não configurou DDNS, esse é o próximo passo obrigatório para garantir que a VPN continue funcionando mesmo quando o IP mudar.

Beyond the Hype: Implementing Neural Networks in Your Backend Workflow

2026-02-11 02:56:17

We often talk about Neural Networks (NNs) in terms of "black boxes," but in 2026, they are just another library in our toolkit like TensorFlow or PyTorch. As a developer focused on Python-based automation and web infrastructure, I've found that the real "magic" happens in the Hidden Layers.
The Practical Use Case: Predictive Web Scaling
Instead of scaling based on CPU thresholds, we can use a simple Multilayer Perceptron (MLP) to:
Ingest historical traffic data as input vectors.
Process patterns through hidden nodes to identify non-linear growth.
Output a scaling command 10 minutes before the traffic spike hits.

My Developer Stack for NN-Driven Automation:
n8n: For orchestrating the data pipeline from APIs to the model.
Python: For the heavy lifting in model training and backpropagation.
React/PHP: For building the interfaces and handlers that act on the model's predictions.
Training these models using Backpropagation ensures that our automation doesn't just work--it learns from its mistakes.
What are you building with Neural Networks this year? Let's discuss in the comments!