feat: create mobile pull requests from pushed branches (Closes #1362)
This commit is contained in:
1 parent
ae98564d9b
commit
e5b9833096
10 files changed
+821
-1
No files matched your search
@@ -0,0 +1,203 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from src import gitea_proxy
|
||||
from src import main
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_pull_creation_operations():
|
||||
main._authored_action_operations.clear()
|
||||
main._idempotency_ledger.clear()
|
||||
yield
|
||||
main._authored_action_operations.clear()
|
||||
main._idempotency_ledger.clear()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pull_creation_options_return_visible_repository_branches(monkeypatch):
|
||||
async def access(repository):
|
||||
assert repository == "stackchain/api"
|
||||
return {"full_name": repository, "default_branch": "main", "permissions": {"push": True}}
|
||||
|
||||
async def branches(repository):
|
||||
assert repository == "stackchain/api"
|
||||
return [
|
||||
{"name": "feature/mobile", "commit": {"id": "abc1234"}},
|
||||
{"name": "main", "commit": {"id": "def5678"}},
|
||||
]
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "repo_branches", branches, raising=False)
|
||||
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/repos/stackchain/api/pull-creation-options")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
assert response.json() == {
|
||||
"default_branch": "main",
|
||||
"branches": [
|
||||
{"name": "feature/mobile", "sha": "abc1234"},
|
||||
{"name": "main", "sha": "def5678"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_create_pull_endpoint_returns_confirmed_mobile_pull(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def access(repository):
|
||||
return {"full_name": repository, "permissions": {"push": True}}
|
||||
|
||||
async def create(repository, *, head, base, title, body, draft, expected_head_sha):
|
||||
calls.append((repository, head, base, title, body, draft, expected_head_sha))
|
||||
return {
|
||||
"number": 42,
|
||||
"repository": repository,
|
||||
"title": title,
|
||||
"body": body,
|
||||
"head": {"ref": head, "sha": expected_head_sha},
|
||||
"base": {"ref": base},
|
||||
"draft": draft,
|
||||
"state": "open",
|
||||
"url": "https://forge.example/stackchain/api/pulls/42",
|
||||
"existing": False,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "create_pull", create, raising=False)
|
||||
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls",
|
||||
headers={"Idempotency-Key": "mobile-create-42"},
|
||||
json={
|
||||
"head": "feature/mobile",
|
||||
"base": "main",
|
||||
"title": " Ship mobile create ",
|
||||
"body": " Context ",
|
||||
"draft": True,
|
||||
"expected_head_sha": "abc1234",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
assert response.json()["number"] == 42
|
||||
assert calls == [
|
||||
("stackchain/api", "feature/mobile", "main", "Ship mobile create", "Context", True, "abc1234")
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_create_pull_revalidates_head_and_confirms_created_pull():
|
||||
requests = []
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if request.method == "GET" and request.url.path.endswith("/branches/feature/mobile"):
|
||||
return httpx.Response(200, json={"name": "feature/mobile", "commit": {"id": "abc1234"}})
|
||||
if request.method == "GET" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(200, json=[])
|
||||
if request.method == "POST" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(201, json={
|
||||
"number": 42,
|
||||
"title": "Ship mobile create",
|
||||
"body": "Context",
|
||||
"state": "open",
|
||||
"draft": True,
|
||||
"head": {"ref": "feature/mobile", "sha": "abc1234"},
|
||||
"base": {"ref": "main"},
|
||||
"user": {"login": "timmy"},
|
||||
"html_url": "https://forge.alexanderwhitestone.com/git/stackchain/api/pulls/42",
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.create_pull(
|
||||
"stackchain/api",
|
||||
head="feature/mobile",
|
||||
base="main",
|
||||
title="Ship mobile create",
|
||||
body="Context",
|
||||
draft=True,
|
||||
expected_head_sha="abc1234",
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["number"] == 42
|
||||
assert result["head"] == {"ref": "feature/mobile", "sha": "abc1234"}
|
||||
assert result["author"] == "timmy"
|
||||
assert result["existing"] is False
|
||||
mutation = next(request for request in requests if request.method == "POST")
|
||||
assert mutation.read() == b'{"head":"feature/mobile","base":"main","title":"Ship mobile create","body":"Context","draft":true}'
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_create_pull_returns_existing_source_base_without_mutation():
|
||||
requests = []
|
||||
existing = {
|
||||
"number": 41,
|
||||
"title": "Already open",
|
||||
"body": "Existing context",
|
||||
"state": "open",
|
||||
"draft": False,
|
||||
"head": {"ref": "feature/mobile", "sha": "abc1234"},
|
||||
"base": {"ref": "main"},
|
||||
"user": {"login": "timmy"},
|
||||
"html_url": "https://forge.alexanderwhitestone.com/git/stackchain/api/pulls/41",
|
||||
}
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if "/branches/" in request.url.path:
|
||||
return httpx.Response(200, json={"name": "feature/mobile", "commit": {"id": "abc1234"}})
|
||||
if request.method == "GET" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(200, json=[existing])
|
||||
return httpx.Response(500)
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.create_pull(
|
||||
"stackchain/api", head="feature/mobile", base="main",
|
||||
title="Duplicate attempt", body="", draft=True,
|
||||
expected_head_sha="abc1234",
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["number"] == 41
|
||||
assert result["existing"] is True
|
||||
assert all(request.method != "POST" for request in requests)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_create_pull_endpoint_reports_stale_source_without_retrying(monkeypatch):
|
||||
async def access(repository):
|
||||
return {"full_name": repository, "permissions": {"push": True}}
|
||||
|
||||
async def stale(*args, **kwargs):
|
||||
raise gitea_proxy.PullCreateConflictError("Source branch changed before pull creation")
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "create_pull", stale)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls",
|
||||
json={
|
||||
"head": "feature/mobile", "base": "main", "title": "Ship it",
|
||||
"expected_head_sha": "abc1234",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert response.json() == {
|
||||
"error": "The source branch changed. Refresh branches before creating the pull request."
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
MODULE = ROOT / "frontend" / "create-pull-sheet.js"
|
||||
|
||||
|
||||
def run_node(scenario: str) -> dict:
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(MODULE))});
|
||||
{scenario}
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], text=True, capture_output=True, cwd=ROOT)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def test_create_pull_controller_loads_branches_and_defaults_base():
|
||||
result = run_node("""
|
||||
const calls=[];
|
||||
const controller=createPullSheet.createController({
|
||||
request:async (url) => {
|
||||
calls.push(url);
|
||||
return {default_branch:'main',branches:[
|
||||
{name:'feature/mobile',sha:'abc1234'},
|
||||
{name:'main',sha:'def5678'}
|
||||
]};
|
||||
},
|
||||
storage:{getItem:()=>null,setItem:()=>{}},
|
||||
login:'timmy'
|
||||
});
|
||||
controller.selectRepository('stackchain/api').then(value => {
|
||||
process.stdout.write(JSON.stringify({value,calls,state:controller.state()}));
|
||||
}).catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["calls"] == ["api/v1/repos/stackchain/api/pull-creation-options"]
|
||||
assert result["state"]["base"] == "main"
|
||||
assert result["state"]["head"] == "feature/mobile"
|
||||
assert result["state"]["expected_head_sha"] == "abc1234"
|
||||
|
||||
|
||||
def test_create_pull_controller_submits_idempotently_and_keeps_draft_on_failure():
|
||||
result = run_node("""
|
||||
const calls=[]; const saved=[]; let fail=true;
|
||||
const controller=createPullSheet.createController({
|
||||
request:async (url, options) => {
|
||||
calls.push([url,options]);
|
||||
if (!options) return {default_branch:'main',branches:[{name:'topic',sha:'abc1234'},{name:'main',sha:'def5678'}]};
|
||||
if (fail) { fail=false; throw new Error('offline'); }
|
||||
return {number:9,repository:'acme/app',head:{ref:'topic',sha:'abc1234'},base:{ref:'main'},draft:true};
|
||||
},
|
||||
storage:{getItem:()=>null,setItem:(key,value)=>saved.push([key,JSON.parse(value)])},
|
||||
login:'timmy', createId:()=> 'stable-id'
|
||||
});
|
||||
(async()=>{
|
||||
await controller.selectRepository('acme/app');
|
||||
controller.update({title:'Ship it',body:'Context'});
|
||||
let error=''; try { await controller.submit(); } catch (caught) { error=caught.message; }
|
||||
const retained=controller.state();
|
||||
const confirmed=await controller.submit();
|
||||
process.stdout.write(JSON.stringify({calls,error,retained,confirmed,saved}));
|
||||
})().catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["error"] == "offline"
|
||||
assert result["retained"]["title"] == "Ship it"
|
||||
posts = [call for call in result["calls"] if call[1]]
|
||||
assert len(posts) == 2
|
||||
assert posts[0][1]["headers"]["Idempotency-Key"] == "stable-id"
|
||||
assert posts[1][1]["headers"]["Idempotency-Key"] == "stable-id"
|
||||
assert posts[0][1]["body"]["expected_head_sha"] == "abc1234"
|
||||
assert result["confirmed"]["number"] == 9
|
||||
|
||||
|
||||
def test_create_pull_controller_restores_only_the_current_accounts_draft():
|
||||
result = run_node("""
|
||||
const values={
|
||||
'stackchain.create-pull.v1.timmy':JSON.stringify({repository:'acme/app',head:'topic',base:'main',title:'Saved title',body:'Saved body',draft:false}),
|
||||
'stackchain.create-pull.v1.alexander':JSON.stringify({repository:'private/repo',title:'Other account'})
|
||||
};
|
||||
const controller=createPullSheet.createController({
|
||||
request:async()=>({}), storage:{getItem:key=>values[key] || null,setItem:()=>{}}, login:'Timmy'
|
||||
});
|
||||
process.stdout.write(JSON.stringify(controller.state()));
|
||||
""")
|
||||
assert result == {
|
||||
"repository": "acme/app",
|
||||
"branches": [],
|
||||
"head": "topic",
|
||||
"base": "main",
|
||||
"expected_head_sha": "",
|
||||
"title": "Saved title",
|
||||
"body": "Saved body",
|
||||
"draft": False,
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_pull_creation_sheet_is_packaged_and_touch_safe():
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
bundle = (ROOT / "src" / "frontend_bundle.py").read_text()
|
||||
|
||||
assert 'id="create-pull-sheet" role="dialog" aria-modal="true"' in html
|
||||
assert 'id="create-pull-form"' in html
|
||||
assert 'id="create-pull-repository"' in html
|
||||
assert 'id="create-pull-head"' in html
|
||||
assert 'id="create-pull-base"' in html
|
||||
assert 'id="submit-create-pull"' in html
|
||||
assert 'static/create-pull-sheet.js' in bundle
|
||||
assert ".create-pull-panel button" in css
|
||||
assert "min-height:44px" in css.replace(" ", "")
|
||||
|
||||
|
||||
def test_create_pull_binding_renders_branch_receipt_and_created_pull():
|
||||
result = run_node("""
|
||||
const rendered=[]; const statuses=[]; const opened=[];
|
||||
const controller={
|
||||
selectRepository:async repository=>({repository,branches:[{name:'topic',sha:'abc1234'},{name:'main',sha:'def5678'}],head:'topic',base:'main',expected_head_sha:'abc1234'}),
|
||||
update:values=>values,
|
||||
submit:async()=>({number:12,repository:'acme/app',existing:false})
|
||||
};
|
||||
const binding=createPullSheet.createBinding({controller,
|
||||
render:state=>rendered.push(state), status:value=>statuses.push(value),
|
||||
onCreated:value=>opened.push(value)
|
||||
});
|
||||
(async()=>{
|
||||
await binding.repositoryChanged('acme/app');
|
||||
await binding.submit();
|
||||
process.stdout.write(JSON.stringify({rendered,statuses,opened}));
|
||||
})().catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["rendered"][0]["expected_head_sha"] == "abc1234"
|
||||
assert result["statuses"][-1] == "Pull request #12 created."
|
||||
assert result["opened"][0]["number"] == 12
|
||||
|
||||
|
||||
def test_dashboard_wires_create_pull_inside_lazy_issue_capture_chunk():
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
module = MODULE.read_text()
|
||||
assert "cp.b();" not in dashboard
|
||||
assert "else cp.b();" in module
|
||||
@@ -1467,6 +1467,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/voice-issue-capture.js",
|
||||
"/dashboard/static/voice-conversation-capture.js",
|
||||
"/dashboard/static/create-issue-sheet.js",
|
||||
"/dashboard/static/create-pull-sheet.js",
|
||||
"/dashboard/static/mobile-create-issue-nav.js",
|
||||
"/dashboard/static/create-and-start.js",
|
||||
"/dashboard/static/assign-and-start.js",
|
||||
|
||||
Reference in new issue
Block a user