









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










UPDATED 2026/2027 EDITION • WEN1 PERFORMANCE ASSESSMENTS • TASK 1 + TASK 2
From Python fundamentals to working automation — DNS, MailHog, Helpdesk API, GitLab, network inventory, reachability, reporting & evidence. Learn the concepts, practice the patterns, then build your own original submission.
This is an independent study guide , not a completed submission and not a copy of any task prompt. Work through Part A for Python, Part B for Task 1 lab skills, Part C for Task 2 skills, then use the checklists in Part D to self-grade your own code before submitting. Always follow your current Course Search / assessment instructions in your nentity-WGU¦canonical_name=Western Governors Universityn student portal for the exact files, endpoints, credentials, and rubric in your cohort — lab IPs, ports, and API details change by version.
setup.sh — venv + deps python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install requests python-dotenv pip freeze > requirements.txt
Concept What to Know / IT Example
Variables snake_case , descriptive: hostname, ip_address, ticket_count. Assignment = binds name to object. No declaration needed.
Types str, int, float, bool, None. Use type() and isinstance(). Cast carefully: int('80') works, int('80a') raises ValueError.
Operators Arithmetic **+ - * / // % **** • Comparison == != < > • Logic and or not • Membership in
F-strings f"{hostname} is {status}" — preferred formatting. Format numbers: f"{pct:.1f}%" , pad: f"{n:03d}".
errors.py — fail gracefully, log clearly import logging, requests logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") log = logging.getLogger(name)
try: r = requests.get(url, timeout=10) r.raise_for_status() except requests.RequestException as e: log.error(f"API failed for {url}: {e}") return [] # or re-raise if task must stop
Topic Pattern to Memorize
GET requests.get(url, headers=..., params=..., timeout=10) → r.status_code , r.json()
POST requests.post(url, json={...}, headers=...) — use json= not data= for JSON APIs
Auth Header: {'Authorization': f'Bearer {token}'} or auth=(user, pass). Token from env, never in code.
Status 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error
Pagination Loop page / next until empty. Collect all pages before reporting.
Timeouts Always set timeout=. No timeout = script can hang forever.
Part B — WEN1 Task 1 Lab Skills
Task 1 is a hands-on lab performance assessment. You are given a small lab environment (often with DNS, a mail catcher like nentity-MailHog¦canonical_name=MailHogn, a helpdesk / ticketing API, and a nentity-GitLab¦canonical_name=GitLabn repo) and asked to write Python that does real work against live services and produces evidence — not just a theory answer. The pattern below repeats in every Task 1 variant: connect → query → validate → act → report → commit.
expected = {"web01": "10.0.0.10", "db01": "10.0.0.20"} for host, want in expected.items(): got = resolve(host) status = "OK" if got == want else f"MISMATCH got={got} want={want}" print(f"{host}: {status}")
TASK 1 EXAM TIP — THE EVIDENCE TRAP Students lose marks not because code fails, but because they cannot prove it ran. For every action, save one artifact: terminal output, API response, nentity-MailHog¦canonical_name=MailHogn screenshot, nentity-GitLab¦canonical_name=GitLabn commit link, or CSV/JSON report. If it isn't saved, it didn't happen for grading.
Part C — WEN1 Task 2 Skills
Task 2 builds on Task 1: less hand-holding, more end-to-end automation. Typical shape: network inventory + reachability + DNS audit + reporting + evidence. You are given (or must build) an inventory, you check what is real, you reconcile differences, and you produce a trustworthy report.
def load_inventory(path): rows, errors = [], [] with open(path, newline='', encoding='utf-8') as f: for i, r in enumerate(csv.DictReader(f), start=2): host = (r.get('hostname') or '').strip().lower() ip = (r.get('ip') or '').strip() try: ipaddress.ip_address(ip) except ValueError: errors.append(f"Row {i}: bad IP {ip!r} for {host}"); continue if not host: errors.append(f"Row {i}: missing hostname"); continue rows.append({'hostname': host, 'ip': ip, 'role': r.get('role','').strip()}) return rows, errors
def tcp_ok(host, port=80, timeout=3): try: with socket.create_connection((host, port), timeout=timeout): return True except OSError: return False
def ping_ok(host): flag = "-n" if platform.system() == "Windows" else "-c" r = subprocess.run(["ping", flag, "1", "-W", "2", host], capture_output=True, text=True, timeout=10) return r.returncode == 0
Symptom Likely Cause → Fix
401 Unauthorized Bad / expired token → re-check env var, regenerate token, print headers (not token) for debug
404 Not Found Wrong base URL / path → copy exact endpoint from task, check trailing slash
Connection refused Service not running / wrong port → check service, curl manually first
KeyError / TypeError API shape changed → print r.json() keys, use .get() with defaults
Script hangs No timeout → add timeout= to every requests / socket call
Works on my machine Hard-coded path / venv → use Path, requirements.txt, README
Part E — 40 Practice Questions + Answers
Q1. Which Python type is best for fast lookup of a device by hostname?
A) List B) Dict C) Tuple D) Set Answer: B — Dict: hostname → device dict gives O(1) lookup; list would need a scan.
Q2. What does socket.gethostbyname('web01') return?
A) MX records B) IPv4 address or raises gaierror C) Ticket ID D) HTML
Answer: B — It resolves an A record to IPv4; on failure it raises socket.gaierror.
Q3. Why use .get('dns','N/A') instead of ['dns']?
A) Faster B) Avoids KeyError if key missing C) Uses less memory D) Required by JSON
Answer: B — .get() returns a default instead of crashing on a missing key.
Q4. Which HTTP status means 'Created'?
A) 200 B) 201 C) 404 D) 500
Answer: B — 201 Created is the correct success code for POST creating a resource.
Q5. What is the purpose of MailHog in Task 1?
A) Send real email B) Capture test email locally without real delivery C) Block spam D) Host DNS Answer: B — nentity-MailHog¦canonical_name=MailHogn catches SMTP locally so you can verify mail safely.
Q6. Best way to store an API token?
A) Hard-code in .py B) Commit to Git C) Environment variable / .env (gitignored) D) In a screenshot Answer: C — Env vars keep secrets out of code and history.
Q7. What does requests.get(..., timeout=10) prevent?
A) 404s B) Hanging forever on a dead server C) JSON errors D) Auth failures Answer: B — Timeout bounds how long you wait for a response.
Q8. Set difference expected - found is useful for?
A) Sorting B) Finding missing hosts in a DNS / inventory audit C) Sending email D) Parsing CSV
Answer: B — Set difference instantly shows missing / extra items.
Q9. Why use 'with open(...) as f:'?
A) Faster B) Auto-closes file, even on error C) Encrypts file D) Required for CSV
Answer: B — Context manager guarantees cleanup.
Q10. What should a report summary include?
A) Only code B) Totals, OK/issues counts, timestamp, how to reproduce C) Secrets D) Only screenshots Answer: B — Summary must let a grader verify scope and outcome at a glance.
Q11. f"{pct:.1f}%" formats a float to?
A) 1 decimal place B) 1 integer C) Hex D) Scientific
Answer: A — .1f = one digit after decimal.
Q12. Which is a pure function?
A) One that prints + writes file B) One that returns a value from inputs, no I/O / globals C) One that uses random D) One that mutates globals Answer: B — Pure = same input → same output, no side effects; easy to test.
Q13. What does r.raise_for_status() do?
A) Prints JSON B) Raises HTTPError for 4xx/5xx C) Retries D) Closes connection Answer: B — It turns error statuses into exceptions you can handle.
Q14. Best verdict for inventory IP != DNS IP?
A) OK B) DNS_MISMATCH C) NOT_IN_INVENTORY D) UNKNOWN
Answer: B — Mismatch means the two sources disagree.
Q15. How to check a TCP port is listening?
A) Ping only B) socket.create_connection((host,port), timeout=...) C) Read CSV D) Check Git
Answer: B — TCP connect proves the port accepts connections.
Q16. Why use pathlib.Path?
A) Faster loops B) Cross-platform paths, readable, / operator C) Required for requests D) Encrypts Answer: B — Path handles Windows / Linux differences and is cleaner than string paths.
Q17. What does csv.DictReader return?
A) README B) requirements.txt (pip freeze) C) .gitignore D) report.csv
Answer: B — requirements.txt documents exact deps for reproducibility.
Q29. What is TTL in DNS?
A) Time to live — how long a record may be cached B) Ticket length C) TCP timeout D) Git log
Answer: A — TTL controls caching; stale cache can explain old values.
Q30. Why avoid bare except:?
A) Slower B) Hides bugs, catches KeyboardInterrupt / SystemExit, makes debugging hard C) Uses memory D) Not allowed in Git
Answer: B — Catch specific exceptions.
Q31. What does ThreadPoolExecutor help with?
A) Sorting B) Checking many hosts concurrently C) Sending email D) Parsing JSON
Answer: B — Parallel I/O for reachability checks.
Q32. What is the best first fix for 401?
A) Change code logic B) Check token / env var, regenerate if expired C) Delete DB D) Reboot router Answer: B — 401 = auth problem, not logic.
Q33. Why use json.dump(..., indent=2)?
A) Faster B) Human-readable, diff-friendly output C) Encrypts D) Compresses
Answer: B — Indented JSON is readable in evidence.
Q34. What does 'r.json()' do?
A) Sends request B) Parses response body as JSON → dict/list C) Closes D) Prints headers
Answer: B — Parses JSON body.
Q35. Which is a good commit message?
A) 'stuff' B) 'Add DNS audit + Helpdesk ticket automation' C) 'asdf' D) 'final_final2'
Answer: B — Clear, verb + scope.
Q36. What should you do before running a script twice?
A) Nothing B) Ensure idempotency — don't create duplicates C) Delete Git D) Change password Answer: B — Re-runs should be safe.
Q37. What does subprocess.run(['ping',...]) return?
A) Bool B) CompletedProcess with returncode, stdout, stderr C) IP D) JSON Answer: B — Check returncode == 0 for success.
Q38. Why use datetime.now(timezone.utc)?
A) Faster B) Unambiguous, timezone-aware timestamps for logs/reports C) Required for CSV D) Shorter
Answer: B — UTC avoids local-time confusion.
Q39. What is the main Task 2 deliverable?
A) Only code B) Code + validated report + evidence proving inventory/reachability/DNS audit C) Only screenshots D) Only README Answer: B — Task 2 is end-to-end: code + report + proof.
Q40. What does 'git status' show?
A) Passwords B) Changed / untracked files, branch C) API keys D) DNS Answer: B — Status shows what would be committed.
Appendix — Cheat Sheets
cheatsheet.py
Error / Code Meaning → Action
NameError Used undefined name → check spelling / import
TypeError Wrong type for operation → print type(x), convert
ValueError Right type, bad value → validate input, e.g. int('abc')
KeyError Missing dict key → use .get(), check API shape
FileNotFoundError Path wrong → print Path.cwd(), use relative Path
401 / 403 Auth / permission → token, role, env var
404 Wrong URL / ID → copy endpoint, check ID exists
500 Server error → check server logs, retry, report