Skip to content

tng-sh/tng-python-public

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

TNG Python - AI-Powered Test Generation

Generate comprehensive test suites for your Python code in minutes using LLM-powered static analysis.

Python Version License

🚀 What is TNG?

TNG analyzes your Python code using Abstract Syntax Tree (AST) parsing to understand your code structure, then uses advanced LLMs to automatically generate comprehensive, production-ready test suites.

Key Features

  • 🧠 Smart Analysis: Deep code intelligence via AST parsing
  • ⚡ Fast: Rust-powered static analysis engine
  • 🎯 Multiple Test Types: Unit, integration, and matrix tests
  • 🔧 Framework Aware: Auto-detects your testing framework
  • 🎨 Beautiful UI: Interactive terminal interface
  • 🌐 Cross-platform: macOS and Linux (x86_64 & ARM64)

📋 Requirements

Python Versions

Version Supported
3.10
3.11
3.12
3.13

Platforms

Platform Architecture Supported
macOS Intel (x86_64)
macOS Apple Silicon (ARM64)
Linux x86_64
Linux ARM64
Windows All

📦 Installation

pip install tng-python

Or with pip3:

pip3 install tng-python

🎯 Quick Start

1. Initialize Configuration

tng-init

This creates a tng_config.py file with auto-detected settings for your project.

2. Configure API Access

Edit tng_config.py and set your API key:

class TngConfig:
    API_KEY = "your_api_key_here"  # Get from https://app.tng.sh
    BASE_URL = "https://api.tng.sh"

3. Generate Tests

Interactive Mode (recommended):

tng

Command Line Mode:

# Generate tests for all methods in a file
tng -f users.py

# Generate test for specific method
tng -f users.py -m create_user

# Short syntax also works
tng f=users.py m=create_user

🎨 Interactive UI Features

The interactive mode provides a beautiful terminal UI with:

File Selection View

  • Search: Real-time fuzzy search through your Python files
  • Filter: Auto-filters out common directories (venv, pycache, etc.)
  • Navigation: Keyboard shortcuts (↑↓ to navigate, Enter to select, q to quit)
  • Preview: Shows file paths to disambiguate files with same names

Method Selection View

  • Lists all functions and methods found in the selected file
  • Shows method context (class name if applicable)
  • Supports classes, functions, async functions, class methods, static methods

Generation Progress

  • Real-time progress updates during test generation
  • Shows current step (analyzing, generating, saving)
  • Displays elapsed time and generation status
  • Visual progress indicators

Post-Generation Menu

After generating tests, you can:

  • Run Tests: Execute the generated tests immediately
  • Copy Command: Copy the test command to clipboard
  • View Results: See test execution results with pass/fail counts
  • Back to Menu: Generate more tests

Test Results View

  • Shows passed, failed, and error counts
  • Displays individual test results
  • Color-coded status indicators
  • Elapsed time for test execution

⚙️ Configuration Guide

TNG auto-detects your project's libraries and frameworks. You can customize or override any settings in tng_config.py.

How Auto-Detection Works

When you run tng-init, TNG:

  1. Scans your dependency files (requirements.txt, pyproject.toml, Pipfile, etc.)
  2. Detects installed packages
  3. Identifies framework-specific files and patterns
  4. Generates tng_config.py with detected settings

⚠️ Important: TNG does its best to auto-detect your setup, but we strongly recommend reviewing and editing tng_config.py to match your actual project configuration.

Customizing Configuration

All settings in tng_config.py can be edited. TNG will use your values instead of auto-detection.

If your library isn't listed: Set the value to "none" or leave it as the closest match. TNG will adapt to your configuration.

Framework Detection

Web Frameworks:

Framework Supported
django
flask
fastapi
sanic
quart
starlette
tornado
bottle
cherrypy
generic

Test Frameworks:

Framework Supported
pytest
unittest
nose2
robotframework
behave
lettuce
hypothesis
ward
green
testify

Configuration:

FRAMEWORK = "django"           # Your web framework
TEST_FRAMEWORK = "pytest"      # Your test framework  
TEST_DIRECTORY = "tests"       # Where tests are saved

Database & ORM

ORMs:

ORM Supported
django-orm
sqlalchemy
peewee
tortoise-orm
sqlmodel
mongoengine
beanie
databases
asyncpg
motor
aioredis
aiopg
aiomysql
none

Databases:

Database Supported
postgresql
mysql
sqlite
mongodb
redis

Cache Systems:

System Supported
redis
memcached

Configuration:

ORM = "sqlalchemy"                # Options: django-orm, sqlalchemy, peewee, tortoise-orm, sqlmodel, mongoengine, beanie, databases, asyncpg, motor, aioredis, aiopg, aiomysql, none
DATABASES = ["postgresql"]        # Auto-detected: postgresql, mysql, sqlite, mongodb, redis
CACHE_SYSTEMS = ["redis"]         # Auto-detected: redis, memcached
ASYNC_DATABASE_SUPPORT = True     # Auto-detected from async drivers

Email Configuration

Email Libraries:

Library Supported
django-email
flask-mail
fastapi-mail
sendgrid
mailgun
postmark
aws-ses
smtplib
none

Configuration:

EMAIL_BACKEND = "sendgrid"             # Options: django-email, flask-mail, fastapi-mail, sendgrid, mailgun, postmark, aws-ses, smtplib, none
EMAIL_PROVIDERS = ["sendgrid", "mailgun"]  # All detected email libraries

Background Jobs

Job Queue Systems:

System Supported
celery
rq
dramatiq
huey
apscheduler
django-q
arq
taskiq
prefect
airflow
ray
dask
none

Configuration:

JOB_QUEUE = "celery"                   # Options: celery, rq, dramatiq, huey, apscheduler, django-q, arq, taskiq, prefect, airflow, ray, dask, none
JOB_SYSTEMS = ["celery", "rq"]         # All detected job systems

Testing & Mocking Libraries

Mock Libraries:

Library Supported
pytest-mock
unittest.mock
mock
flexmock
none

HTTP Mocking:

Library Supported
responses
httpretty
requests-mock
vcr
none

Factory/Fixture Libraries:

Library Supported
factory_boy
mixer
model_bakery
fixtures
none

Configuration:

MOCK_LIBRARY = "pytest-mock"           # Options: pytest-mock, unittest.mock, mock, flexmock, none
HTTP_MOCK_LIBRARY = "responses"        # Options: responses, httpretty, requests-mock, vcr, none  
FACTORY_LIBRARY = "factory_boy"        # Options: factory_boy, mixer, model_bakery, fixtures, none

Authentication & Authorization

Authentication:

Library Supported
django-auth
flask-login
fastapi-users
none

Authorization:

Library Supported
django-guardian
flask-principal
casbin
none

Configuration:

AUTHENTICATION_ENABLED = True          # Enable if using auth
AUTH_LIBRARY = "django-auth"           # Auth library (or "none")
AUTHORIZATION_ENABLED = True           # Enable if using authz
AUTHZ_LIBRARY = "django-guardian"      # Authz library (or "none")

Configuring Authentication Methods

⚠️ Important: If your app uses authentication, you must configure AUTHENTICATION_METHODS in tng_config.py.

TNG needs to know which authentication decorators/functions your app uses to generate proper test mocks. Uncomment and configure:

AUTHENTICATION_METHODS = [
    {
        "method": "login_required",           # Auth decorator/function name
        "file_location": "flask_login",       # Module where it's imported from
        "auth_type": "session"                # Authentication type
    },
    {
        "method": "jwt_required",
        "file_location": "flask_jwt_extended",
        "auth_type": "jwt"
    }
]

Required Fields:

  • method - Name of your auth decorator or function (e.g., login_required, get_current_user)
  • file_location - Module path or file where defined (e.g., flask_login or app/auth.py)
  • auth_type - Type of authentication used

Supported Auth Types: sessionjwttoken_authbasic_authoauthheaderscustom

Examples by Framework:

Django:

AUTHENTICATION_METHODS = [
    {
        "method": "login_required",
        "file_location": "django.contrib.auth.decorators",
        "auth_type": "session"
    },
    {
        "method": "permission_required",
        "file_location": "django.contrib.auth.decorators",
        "auth_type": "session"
    }
]

Flask:

AUTHENTICATION_METHODS = [
    {
        "method": "login_required",
        "file_location": "flask_login",
        "auth_type": "session"
    },
    {
        "method": "jwt_required",
        "file_location": "flask_jwt_extended",
        "auth_type": "jwt"
    }
]

FastAPI:

AUTHENTICATION_METHODS = [
    {
        "method": "get_current_user",
        "file_location": "app/auth.py",
        "auth_type": "jwt"
    },
    {
        "method": "get_current_active_user",
        "file_location": "app/auth.py",
        "auth_type": "jwt"
    }
]

Custom Auth:

AUTHENTICATION_METHODS = [
    {
        "method": "authenticate_user",
        "file_location": "app/auth.py",
        "auth_type": "session"
    },
    {
        "method": "require_api_key",
        "file_location": "app/middleware.py",
        "auth_type": "headers"
    }
]

If you don't use authentication:

AUTHENTICATION_ENABLED = False
# No need to configure AUTHENTICATION_METHODS

How to Add a Library

TNG auto-detects libraries from your dependencies. To ensure detection:

Option 1: Add to dependencies (recommended)

# For pip
echo "celery>=5.0" >> requirements.txt

# For poetry
poetry add celery

# For pip with pyproject.toml
# Add to [project.dependencies] in pyproject.toml

Option 2: Manually set in config

# In tng_config.py
class TngConfig:
    JOB_QUEUE = "celery"  # Manually specify
    JOB_SYSTEMS = ["celery", "rq"]  # Add multiple

Option 3: Re-run init

# After adding dependencies, regenerate config
tng-init
# Choose 'y' to overwrite existing config

Configuration Priority

  1. Manual settings in tng_config.py (highest priority)
  2. Environment variables (e.g., TNG_API_KEY)
  3. Auto-detection (lowest priority)

TNG will always use your explicit settings over auto-detected values.


📝 CLI Commands

Main Commands

tng                           # Interactive mode
tng -f <file>                 # Generate tests for file
tng -f <file> -m <method>     # Generate test for specific method
tng-init                      # Initialize configuration
tng --version                 # Show version

Options

  • -f, --file: File name or path to generate tests for
  • -m, --method: Specific method/function to generate test for
  • -v, --version: Show version and exit

Examples

# Interactive mode (easiest)
tng

# Generate tests for users.py
tng -f users.py

# Generate test for create_user method in users.py
tng -f users.py -m create_user

# Works with paths too
tng -f app/services/users.py -m create_user

# Short syntax
tng f=users.py m=create_user

🔍 How TNG Works

  1. Static Analysis: TNG uses Rust-powered AST parsing to analyze your Python code
  2. Context Gathering: Collects information about:
  • Function signatures and parameters
    • Class hierarchies and relationships
  • Import dependencies
    • Framework conventions
    • Database models and ORM patterns
  1. Test Generation: Sends context to LLM which generates:
    • Appropriate test structure for your framework
    • Mocks for dependencies
    • Edge cases and error scenarios
    • Fixtures and setup code
  2. File Management: Automatically:
    • Creates test files in correct location
    • Names tests appropriately
    • Handles imports
    • Organizes by your project's conventions

🎯 What Tests Are Generated?

Unit Tests

  • Individual function/method behavior
  • Edge cases and boundary conditions
  • Error handling and exceptions
  • Return value validation

Integration Tests

  • Component interactions
  • Database queries
  • API calls
  • Service dependencies

Matrix Tests

  • Multiple input combinations
  • Cross-cutting concerns
  • Complex scenarios

📂 Project Structure Requirements

TNG works with any Python project structure. Common patterns:

project/
├── app/              # Source code
│   ├── models.py
│   ├── views.py
│   └── services.py
├── tests/            # Tests (auto-detected)
│   ├── test_models.py
│   ├── test_views.py
│   └── test_services.py
├── requirements.txt  # Dependencies (auto-detected)
├── pyproject.toml    # Or Poetry/UV config
└── tng_config.py     # TNG configuration

TNG auto-detects:

  • Test directory location (tests/, test/, spec/, etc.)
  • Dependency files (requirements.txt, pyproject.toml, Pipfile, etc.)
  • Framework and testing conventions

🛠️ Advanced Usage

Custom Configuration

You can override auto-detection in tng_config.py:

class TngConfig:
    # Force specific framework even if auto-detection differs
    FRAMEWORK = "django"
    TEST_FRAMEWORK = "pytest"
    
    # Custom test directory
    TEST_DIRECTORY = "spec"
    
    # Specify ORM and database
    ORM = "sqlalchemy"
    DATABASES = ["postgresql"]
    
    # Mock preferences
    MOCK_LIBRARY = "unittest.mock"
    HTTP_MOCK_LIBRARY = "responses"

Environment Variables

Set API key via environment variable:

export TNG_API_KEY="your_api_key"

🐛 Troubleshooting

"No API key found"

  • Run tng-init to create config file
  • Set API_KEY in tng_config.py
  • Or set TNG_API_KEY environment variable

"No Python files found"

  • Ensure you're in your project directory
  • TNG searches current directory recursively
  • Excludes common directories (venv, pycache, etc.)

"Failed to analyze file"

  • Check that file has valid Python syntax
  • Ensure file is not in excluded directory
  • Try specifying full path: tng -f /full/path/to/file.py

Platform Issues

  • macOS: Works on Intel and Apple Silicon
  • Linux: Requires glibc 2.34+ (Ubuntu 22.04+, Debian 12+)
  • Windows: Not currently supported

📄 License

Commercial License - See LICENSE file for details.

This software is proprietary and confidential to Binary Dreams LLC.


🤝 Support


🔒 Security & Privacy

  • Code analysis happens locally (static AST parsing)
  • Only analyzed context (not full source) sent to API
  • All API communication over HTTPS
  • No code stored on servers after generation
  • See our privacy policy at https://tng.sh/privacy

Built with ❤️ using Rust and Python

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published