Test ortamında OTPMOCK_URL=https://api.otpmock.com tanımlayın, Bandwidth istemcisini bu adrese yönlendirin ve Bandwidth kimlik bilgisi olarak otpmock API anahtarınızı kullanın. Uygulama kodunuz değişmez; canlı ortam Bandwidth ile göndermeye devam eder.
Kurulum
SDK'nın basePath seçeneği mesaj gönderirken yok sayılır, çünkü her işlemin kendi sunucu adresi vardır. Test ortamında uygulama başlarken bir kez bandwidth-sdk/dist/base içinden o adresi değiştirin.
import { Configuration, MessagesApi } from "bandwidth-sdk";
import { operationServerMap } from "bandwidth-sdk/dist/base";
if (process.env.OTPMOCK_URL) {
operationServerMap["MessagesApi.createMessage"][0].url = `${process.env.OTPMOCK_URL}/api/v2`;
}
export const bandwidth = new MessagesApi(
new Configuration({
username: process.env.BANDWIDTH_USERNAME,
password: process.env.BANDWIDTH_PASSWORD, // testte: otpmock API anahtarı
}),
);import os
from urllib.parse import urlparse
import bandwidth
class OtpMockApiClient(bandwidth.ApiClient):
"""Each Bandwidth operation has its own host; send them all to otpmock."""
def call_api(self, method, url, *args, **kwargs):
u = urlparse(url)
url = os.environ["OTPMOCK_URL"].rstrip("/") + u.path + ("?" + u.query if u.query else "")
return super().call_api(method, url, *args, **kwargs)
config = bandwidth.Configuration(
username=os.environ["BANDWIDTH_USERNAME"],
password=os.environ["BANDWIDTH_PASSWORD"], # testte: otpmock API anahtarı
)
client = OtpMockApiClient(config) if os.environ.get("OTPMOCK_URL") else bandwidth.ApiClient(config)
messages = bandwidth.MessagesApi(client)String base = System.getenv().getOrDefault("OTPMOCK_URL", "https://messaging.bandwidth.com");
String auth = Base64.getEncoder().encodeToString(
(System.getenv("BANDWIDTH_USERNAME") + ":" + System.getenv("BANDWIDTH_PASSWORD")).getBytes()); // password = testte: otpmock API anahtarı
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/api/v2/users/" + accountId + "/messages"))
.header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json)) // {"applicationId":"...","to":["+1..."],"from":"+1...","text":"..."}
.build();// The Bandwidth .NET package has no host option, so call the Messaging API directly.
var baseUrl = Environment.GetEnvironmentVariable("OTPMOCK_URL") ?? "https://messaging.bandwidth.com";
var accountId = Environment.GetEnvironmentVariable("BANDWIDTH_ACCOUNT_ID");
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(
$"{Environment.GetEnvironmentVariable("BANDWIDTH_USERNAME")}:{Environment.GetEnvironmentVariable("BANDWIDTH_PASSWORD")}")); // password = otpmock key in tests
using var http = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/api/v2/users/{accountId}/messages")
{
Content = JsonContent.Create(new { applicationId, to = new[] { phone }, from, text }),
};
req.Headers.Authorization = new AuthenticationHeaderValue("Basic", auth);
(await http.SendAsync(req)).EnsureSuccessStatusCode();use Bandwidth\Api\MessagesApi;
use Bandwidth\Configuration;
use GuzzleHttp\{Client, HandlerStack, Middleware};
use Psr\Http\Message\RequestInterface;
// createMessage has its own server URL, so tests swap the host on the Guzzle client.
$stack = HandlerStack::create();
if ($otpmock = getenv('OTPMOCK_URL')) {
$u = parse_url($otpmock);
$stack->push(Middleware::mapRequest(fn (RequestInterface $r) => $r->withUri(
$r->getUri()->withScheme($u['scheme'])->withHost($u['host'])->withPort($u['port'] ?? null))));
}
$config = (new Configuration())
->setUsername(getenv('BANDWIDTH_USERNAME'))
->setPassword(getenv('BANDWIDTH_PASSWORD')); // testte: otpmock API anahtarı
$bandwidth = new MessagesApi(new Client(['handler' => $stack]), $config);require "net/http"
require "json"
BANDWIDTH_URL = ENV.fetch("OTPMOCK_URL", "https://messaging.bandwidth.com")
uri = URI("#{BANDWIDTH_URL}/api/v2/users/#{ENV["BANDWIDTH_ACCOUNT_ID"]}/messages")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.basic_auth(ENV["BANDWIDTH_USERNAME"], ENV["BANDWIDTH_PASSWORD"]) # password = testte: otpmock API anahtarı
req.body = { applicationId: ENV["BANDWIDTH_APP_ID"], to: ["+15550142"], from: "+15550000001", text: "Your code is #{code}" }.to_json
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }// Bandwidth has no official Go SDK; call its HTTP API with net/http, only the host changes.
base := os.Getenv("OTPMOCK_URL")
if base == "" {
base = "https://messaging.bandwidth.com"
}
body, _ := json.Marshal(map[string]any{
"applicationId": os.Getenv("BANDWIDTH_APPLICATION_ID"), "to": []string{"+15550142"},
"from": os.Getenv("BANDWIDTH_NUMBER"), "text": msg,
})
req, _ := http.NewRequest("POST", base+"/api/v2/users/"+os.Getenv("BANDWIDTH_ACCOUNT_ID")+"/messages", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(os.Getenv("BANDWIDTH_USERNAME"), os.Getenv("BANDWIDTH_PASSWORD")) // password = otpmock key in tests
res, err := http.DefaultClient.Do(req) // 202 AcceptedHer dil, CI'da sağlayıcının resmi SDK'sıyla (ya da başka bir adrese yönlendirilemeyen SDK'larda düz HTTP API'siyle) otpmock'a karşı sınanır.
Kimlik bilgisi. Test ortamında otpmock API anahtarınızı Bandwidth parolası olarak kullanın (Basic kimlik doğrulaması). Testlerde OAuth istemci kimlik bilgilerini ayarlamayın.
otpmock neyi taklit ediyor?
| Uç nokta | Ne yapar |
|---|---|
POST /api/v2/users/{accountId}/messages | Mesaj gönderir (applicationId, to[], from, text), 202 |
Yanıtlar ve hatalar Bandwidth API'sinin kendi biçimindedir, bu yüzden istemci kütüphanesi onları her zamanki gibi çözümler. Yanlış anahtar ve aylık hakkın dolması da aynı hata biçimiyle döner.
Telefon numaraları
E.164 biçiminde (+15550142) gönderin.
Testinizde kodu okuyun
const telefon = otp.randomPhone(); // her test için ayrı numara
const since = Date.now() - 5_000;
await page.getByRole("button", { name: "Kod gönder" }).click(); // uygulamanız Bandwidth API'sini çağırır
const { code } = await otp.waitForCode(telefon, { since });otp yardımcısı bağımlılığı olmayan tek bir dosyadır: dokümandan alın (İngilizce). Baştan sona örnekler: Playwright ve Cypress rehberleri (İngilizce).
Sık sorulanlar
otpmock Bandwidth üzerinden gerçek SMS gönderiyor mu?
Hayır. Test ortamında uygulamanızın Bandwidth istekleri otpmock'a gider; mesaj 10 dakika saklanır ve Bandwidth ya da herhangi bir operatör ağına hiç ulaşmaz. Canlı ortamınız Bandwidth kullanmaya devam eder, çünkü otpmock yalnızca OTPMOCK_URL tanımlıyken devreye girer.
Resmi bandwidth-sdk SDK'sı destekleniyor mu?
Evet. Bandwidth uç noktaları, resmi bandwidth-sdk paketiyle Node.js'te uçtan uca sınanır. Adres değiştirmeye izin veren başka dillerdeki istemciler de çalışır.
otpmock hangi Bandwidth API'lerini destekliyor?
POST /api/v2/users/{accountId}/messages (Mesaj gönderir (applicationId, to[], from, text), 202).
Ücretsiz plan ayda 300 mesaj içerir, kart gerekmez. Yapay zeka kodlama asistanı mı kullanıyorsunuz? otpmock.com/llms-full.txt adresini verin.
Ücretsiz API anahtarı al